Šiame straipsnyje sužinosite viską apie „Python“ rinkinius. Tiksliau, kas yra rinkiniai, kaip juos sukurti, kada juos naudoti ir įvairūs metodai, kuriuos turėtumėte žinoti.
Vaizdo įrašas: „Python“ sąrašai ir rinkiniai
„Python“ paketas yra panašus į sąrašą. Skirtumas tarp šių dviejų yra tas, kad mes negalime pakeisti paketo elementų, kai jis yra priskirtas, o mes galime pakeisti sąrašo elementus.
„Tuple“ kūrimas
Sudedama visi elementai (elementai) skliausteliuose ()
, atskirti kableliais. Skliausteliai yra neprivalomi, tačiau juos naudoti yra gera praktika.
Tuple gali būti bet koks elementų skaičius ir jie gali būti skirtingų tipų (sveikasis skaičius, plūduriuojantis, sąrašas, eilutė ir kt.).
# 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)
Rezultatas
() (1, 2, 3) (1, „Labas“, 3.4) („pelė“, (8, 4, 6), (1, 2, 3))
Taip pat galima sukurti skliaustą nenaudojant skliaustų. Tai vadinama paketiniu paketu.
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
Rezultatas
(3, 4,6, „šuo“) 3 4,6 šuo
Sukurti dviejų elementų elementą yra šiek tiek keblu.
Vieno elemento skliaustuose nepakanka. Mums reikės galinio kablelio, kuris nurodys, kad tai iš tikrųjų yra dvigubas.
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)) #
Rezultatas
Prisijunkite prie „Tuple Elements“
Yra keli būdai, kuriais mes galime pasiekti du elementus.
1. Indeksavimas
Mes galime naudoti indekso operatorių, ()
norėdami pasiekti elementą keliuose, kurių indeksas prasideda nuo 0.
Taigi, elementų, turinčių 6 elementus, indeksai bus nuo 0 iki 5. Pabandžius pasiekti indeksą, esantį ne dvigubo indekso diapazone (šiame pavyzdyje 6,7, …), pakils IndexError
.
Indeksas turi būti sveikasis skaičius, todėl negalime naudoti „float“ ar kitų tipų. Tai lems TypeError
.
Panašiai į įdėtus rinkinius galima patekti naudojant įdėtą indeksavimą, kaip parodyta toliau pateiktame pavyzdyje.
# 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
Rezultatas
4 taškai
2. Neigiamas indeksavimas
„Python“ leidžia neigiamą savo sekų indeksavimą.
Rodiklis -1 nurodo paskutinį elementą, -2 - antrą paskutinį elementą ir pan.
# 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))
Rezultatas
tp
3. Pjaustymas
Naudodamiesi pjaustymo operatoriaus dvitaškiu, mes galime pasiekti daugybę elementų vienete :
.
# 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(:))
Rezultatas
(„r“, „o“, „g“) („p“, „r“) („i“, „z“) („p“, „r“, „o“, „g“, „r“ („a“, „m“, „i“, „z“)
Pjaustymą galima geriausiai vizualizuoti, laikant indeksą tarp elementų, kaip parodyta žemiau. Taigi, jei norime pasiekti diapazoną, mums reikia indekso, kuris išpjaus dalį iš paketo.

Tuple keitimas
Skirtingai nuo sąrašų, rinkiniai yra nekintami.
Tai reiškia, kad po kelis elementus jų pakeisti negalima. Bet jei pats elementas yra kintamas duomenų tipas, pvz., Sąrašas, jo įdėtus elementus galima pakeisti.
Taip pat galime priskirti po porą skirtingų verčių (perskirstymas).
# 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)
Rezultatas
(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:
- Dažniausiai heterogeniniams (skirtingiems) duomenų tipams naudojame rinkinius, o vienarūšiams (panašiems) duomenų tipams - sąrašus.
- Kadangi rinkiniai yra nekintami, kartojimasis per du kartus yra greitesnis nei su sąrašu. Taigi yra nedidelis našumas.
- Rinkiniai, kuriuose yra nekintamų elementų, gali būti naudojami kaip raktas žodynui. Turint sąrašus, tai neįmanoma.
- Jei turite duomenų, kurie nesikeičia, įdiegę juos kaip paketus garantuosite, kad jie išliks apsaugoti nuo rašymo.