Python Tuple (esimerkkien kanssa)

Tässä artikkelissa opit kaiken Python-sarjoista. Tarkemmin sanottuna mitkä ovat joukot, miten ne luodaan, milloin niitä käytetään ja mitä erilaisia ​​menetelmiä sinun tulisi tuntea.

Video: Python-luettelot ja tuplit

Pythonissa oleva dupleksi on samanlainen kuin luettelo. Ero näiden kahden välillä on se, että emme voi muuttaa dupleksin osia, kun se on määritetty, kun taas voimme muuttaa luettelon elementtejä.

Tuplen luominen

Sarja luodaan sijoittamalla kaikki kohteet (elementit) sulkeisiin ()pilkuilla erotettuna. Sulkeet ovat valinnaisia, mutta on hyvä käyttää niitä.

Tuplassa voi olla mikä tahansa määrä kohteita ja ne voivat olla erityyppisiä (kokonaisluku, kelluva, luettelo, merkkijono jne.).

 # 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)

Tuotos

 () (1, 2, 3) (1, Hei, 3.4) ('hiiri', (8, 4, 6), (1, 2, 3))

Nuppi voidaan myös luoda ilman sulkeita. Tätä kutsutaan kaksoispakkaukseksi.

 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

Tuotos

 (3, 4.6, 'koira') 3 4.6 koira

Yhdellä elementillä varustetun dupleksin luominen on vähän hankalaa.

Yhden elementin pitäminen sulkeissa ei riitä. Tarvitsemme loppupilkun osoittamaan, että se on itse asiassa kaksinkertainen.

 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)) # 

Tuotos

 

Käytä Tuple Elements -sovellusta

On olemassa useita tapoja, joilla voimme käyttää dupleksin elementtejä.

1. Indeksointi

Voimme käyttää hakemisto-operaattoria ()pääsemään kohteeseen sarjassa, jossa hakemisto alkaa nollasta.

Joten kuuden elementin omaavalla sekvenssillä on indeksit välillä 0 - 5. Yritetään päästä hakemistoon, joka on kaksoisindeksialueen ulkopuolella (tässä esimerkissä 6,7, …) IndexError.

Indeksin on oltava kokonaisluku, joten emme voi käyttää float- tai muita tyyppejä. Tämä johtaa TypeError.

Samoin sisäkkäisiin joukkoihin pääsee käyttämällä sisäkkäistä indeksointia, kuten alla olevassa esimerkissä on esitetty.

 # 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

Tuotos

 kohdat 4

2. Negatiivinen indeksointi

Python sallii negatiivisen indeksoinnin sekvensseilleen.

Indeksi -1 viittaa viimeiseen, -2 toiseen viimeiseen kohtaan ja niin edelleen.

 # 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))

Tuotos

 tp

3. Viipalointi

Voimme käyttää useita tuotteita sarjassa käyttämällä viipalointioperaattorin kaksoispistettä :.

 # 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(:))

Tuotos

 ('r', 'o', 'g') ('p', 'r') ('i', 'z') ('p', 'r', 'o', 'g', 'r ',' a ',' m ',' i ',' z ')

Viipalointi voidaan parhaiten visualisoida katsomalla, että indeksi on elementtien välillä, kuten alla on esitetty. Joten jos haluamme käyttää aluetta, tarvitsemme indeksin, joka leikkaa osan dupleksista.

Elementin viipalointi Pythonissa

Tuplen vaihtaminen

Toisin kuin luettelot, joukot ovat muuttumattomia.

Tämä tarkoittaa, että dupleksin elementtejä ei voi muuttaa, kun ne on määritetty. Mutta jos elementti itsessään on muutettava tietotyyppi, kuten luettelo, sen sisäkkäisiä kohteita voidaan muuttaa.

Voimme myös määrittää sekvenssin eri arvoille (uudelleenmääritys).

 # 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)

Tuotos

 (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:

  • Käytämme yleensä joukkoa heterogeenisille (erilaisille) tietotyypeille ja luetteloita homogeenisille (samanlaisille) tietotyypeille.
  • Koska joukot ovat muuttumattomia, iterointi dupleksin läpi on nopeampaa kuin luettelon kanssa. Joten suorituskyky paranee hieman.
  • Vaihtumattomia elementtejä sisältäviä joukkoja voidaan käyttää avainsanana sanakirjassa. Luetteloiden kanssa tämä ei ole mahdollista.
  • Jos sinulla on tietoja, jotka eivät muutu, niiden käyttöönotto kaksinkertaisena takaa, että ne pysyvät kirjoitussuojatuina.

Mielenkiintoisia artikkeleita...