Šajā rakstā jūs uzzināsiet visu par Python atsaucēm. Precīzāk, kas ir komplekti, kā tos izveidot, kad tos izmantot, un dažādas metodes, kas jums būtu jāpārzina.
Video: Python saraksti un apkopojumi
Virsraksts Python ir līdzīgs sarakstam. Atšķirība starp abām ir tā, ka mēs nevaram mainīt kopas elementus, kad tas ir piešķirts, turpretī mēs varam mainīt saraksta elementus.
Tuple izveidošana
Tiek izveidots korpuss, visus elementus (elementus) ievietojot iekavās ()
, atdalot tos ar komatiem. Iekavas nav obligātas, tomēr to lietošana ir laba prakse.
Dubultā var būt jebkura vienumu skaits, un tie var būt dažāda veida (vesels skaitlis, pludiņš, saraksts, virkne utt.).
# Different types of tuples # Empty tuple my_tuple = () print(my_tuple) # Tuple having integers my_tuple = (1, 2, 3) print(my_tuple) # tuple with mixed datatypes my_tuple = (1, "Hello", 3.4) print(my_tuple) # nested tuple my_tuple = ("mouse", (8, 4, 6), (1, 2, 3)) print(my_tuple)
Rezultāts
() (1, 2, 3) (1, “Sveiki”, 3.4) (“pele”, (8, 4, 6), (1, 2, 3))
Virsotni var izveidot arī, neizmantojot iekavas. Tas ir pazīstams kā dubultā iesaiņošana.
my_tuple = 3, 4.6, "dog" print(my_tuple) # tuple unpacking is also possible a, b, c = my_tuple print(a) # 3 print(b) # 4.6 print(c) # dog
Rezultāts
(3, 4.6, 'suns') 3 4.6 suns
Veidot dubultu ar vienu elementu ir mazliet sarežģīti.
Nepietiek ar to, ka iekavās ir viens elements. Mums būs nepieciešams pēdējais komats, lai norādītu, ka tas faktiski ir dubultā.
my_tuple = ("hello") print(type(my_tuple)) # # Creating a tuple having one element my_tuple = ("hello",) print(type(my_tuple)) # # Parentheses is optional my_tuple = "hello", print(type(my_tuple)) #
Rezultāts
Piekļūstiet Tuple Elements
Ir dažādi veidi, kā mēs varam piekļūt kopas elementiem.
1. Indeksēšana
Mēs varam izmantot indeksa operatoru, ()
lai piekļūtu vienumam dubultā, kur indekss sākas no 0.
Tātad, pakešu ar 6 elementiem indeksi būs no 0 līdz 5. Mēģinot piekļūt indeksam, kas atrodas ārpus dubulto indeksu diapazona (šajā piemērā 6,7, …), tas paaugstinās IndexError
.
Indeksam jābūt veselam skaitlim, tāpēc mēs nevaram izmantot pludiņus vai citus veidus. Tā rezultātā TypeError
.
Tāpat ligzdotajiem komplektiem var piekļūt, izmantojot ligzdoto indeksēšanu, kā parādīts zemāk esošajā piemērā.
# Accessing tuple elements using indexing my_tuple = ('p','e','r','m','i','t') print(my_tuple(0)) # 'p' print(my_tuple(5)) # 't' # IndexError: list index out of range # print(my_tuple(6)) # Index must be an integer # TypeError: list indices must be integers, not float # my_tuple(2.0) # nested tuple n_tuple = ("mouse", (8, 4, 6), (1, 2, 3)) # nested index print(n_tuple(0)(3)) # 's' print(n_tuple(1)(1)) # 4
Rezultāts
4. punkts
2. Negatīva indeksēšana
Python pieļauj negatīvu indeksēšanu savām sekvencēm.
Indekss -1 attiecas uz pēdējo vienumu, -2 uz otro pēdējo vienumu un tā tālāk.
# Negative indexing for accessing tuple elements my_tuple = ('p', 'e', 'r', 'm', 'i', 't') # Output: 't' print(my_tuple(-1)) # Output: 'p' print(my_tuple(-6))
Rezultāts
tp
3. Sagriešana
Mēs varam piekļūt virknei vienumu vienā komplektā, izmantojot sagriešanas operatora kolu :
.
# Accessing tuple elements using slicing my_tuple = ('p','r','o','g','r','a','m','i','z') # elements 2nd to 4th # Output: ('r', 'o', 'g') print(my_tuple(1:4)) # elements beginning to 2nd # Output: ('p', 'r') print(my_tuple(:-7)) # elements 8th to end # Output: ('i', 'z') print(my_tuple(7:)) # elements beginning to end # Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') print(my_tuple(:))
Rezultāts
('r', 'o', 'g') ('p', 'r') ('i', 'z') ('p', 'r', 'o', 'g', 'r ',' a ',' m ',' i ',' z ')
Sagriešanu vislabāk var vizualizēt, uzskatot, ka indekss atrodas starp elementiem, kā parādīts zemāk. Tātad, ja mēs vēlamies piekļūt diapazonam, mums ir nepieciešams indekss, kas sagriež daļu no kopas.

Tuples maiņa
Atšķirībā no sarakstiem, korekcijas nav maināmas.
Tas nozīmē, ka kopas elementus nevar mainīt, kad tie ir piešķirti. Bet, ja elements pats par sevi ir maināms datu tips, piemēram, saraksts, tā ligzdotos vienumus var mainīt.
Mēs varam arī piešķirt dubultu dažādām vērtībām (pārdalīšana).
# Changing tuple values my_tuple = (4, 2, 3, (6, 5)) # TypeError: 'tuple' object does not support item assignment # my_tuple(1) = 9 # However, item of mutable element can be changed my_tuple(3)(0) = 9 # Output: (4, 2, 3, (9, 5)) print(my_tuple) # Tuples can be reassigned my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') # Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') print(my_tuple)
Rezultāts
(4, 2, 3, (9, 5)) ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
We can use +
operator to combine two tuples. This is called concatenation.
We can also repeat the elements in a tuple for a given number of times using the *
operator.
Both +
and *
operations result in a new tuple.
# Concatenation # Output: (1, 2, 3, 4, 5, 6) print((1, 2, 3) + (4, 5, 6)) # Repeat # Output: ('Repeat', 'Repeat', 'Repeat') print(("Repeat",) * 3)
Output
(1, 2, 3, 4, 5, 6) ('Repeat', 'Repeat', 'Repeat')
Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. It means that we cannot delete or remove items from a tuple.
Deleting a tuple entirely, however, is possible using the keyword del.
# Deleting tuples my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') # can't delete items # TypeError: 'tuple' object doesn't support item deletion # del my_tuple(3) # Can delete an entire tuple del my_tuple # NameError: name 'my_tuple' is not defined print(my_tuple)
Output
Traceback (most recent call last): File "", line 12, in NameError: name 'my_tuple' is not defined
Tuple Methods
Methods that add items or remove items are not available with tuple. Only the following two methods are available.
Some examples of Python tuple methods:
my_tuple = ('a', 'p', 'p', 'l', 'e',) print(my_tuple.count('p')) # Output: 2 print(my_tuple.index('l')) # Output: 3
Output
2 3
Other Tuple Operations
1. Tuple Membership Test
We can test if an item exists in a tuple or not, using the keyword in
.
# Membership test in tuple my_tuple = ('a', 'p', 'p', 'l', 'e',) # In operation print('a' in my_tuple) print('b' in my_tuple) # Not in operation print('g' not in my_tuple)
Output
True False True
2. Iterating Through a Tuple
We can use a for
loop to iterate through each item in a tuple.
# Using a for loop to iterate through a tuple for name in ('John', 'Kate'): print("Hello", name)
Output
Hello John Hello Kate
Advantages of Tuple over List
Since tuples are quite similar to lists, both of them are used in similar situations. However, there are certain advantages of implementing a tuple over a list. Below listed are some of the main advantages:
- Parasti mēs izmantojam heterogēnu (dažādu) datu tipu kopas un homogēnu (līdzīgu) datu tipu sarakstus.
- Tā kā kopas nav maināmas, iterācija caur kopu ir ātrāka nekā ar sarakstu. Tātad ir neliels veiktspējas pieaugums.
- Vārdnīcas, kas satur nemaināmus elementus, var izmantot kā atslēgas vārdnīcai. Izmantojot sarakstus, tas nav iespējams.
- Ja jums ir dati, kas nemainās, to ieviešana kā kopa garantēs, ka tie paliks aizsargāti pret rakstīšanu.