Awọn ọmọ wẹwẹ Python

Ni Python, tuple jẹ ikojọpọ eyiti o jẹ paṣẹ ati aiyipada . Iyẹn tumọ si pe a ko le ṣafikun tabi yọ awọn ohun kan kuro ni tuple.

A ṣẹda tuples nipa lilo akomo () ati pe o kere ju aami ami ami kan ( , ).

Awọn ọmọ wẹwẹ le jẹ atọka ati ge gege bi awọn atokọ, ayafi pe abajade ti ege naa yoo tun jẹ tuple.




Bii o ṣe Ṣẹda Tuple kan

colorsTuple = ('red', 'green', 'blue') print(colorsTuple)

Ijade:

('red', 'green', 'blue')

Ṣiṣẹda Tuple Pẹlu Ohunkan Kan

Awọn ọmọ wẹwẹ beere o kere ju aami idẹsẹ kan, nitorinaa lati ṣẹda tuple pẹlu ohun kan ṣoṣo, o ni fi aami idẹsẹ kan lẹhin nkan naa. Fun apere:


colorsTuple = ('red',)

Bii a ṣe le Wọle si Awọn ohun kan ti Tuple

A le wọle si awọn ohun elo tuple nipa tọka si nọmba itọka:

colorsTuple = ('red', 'green', 'blue') print(colorsTuple[2])

Ijade:

blue

Wọle si Ibiti Awọn ohun kan (Sisọ)

A le ṣọkasi ibiti awọn ohun kan wa lati tuple nipa sisọ atọka ibẹrẹ ati itọka ipari. A lo awọn : onišẹ.

Akiyesi:Iye ipadabọ yoo tun jẹ tuple pẹlu awọn ohun kan ti a ṣalaye. colorsTuple = ('red', 'green', 'blue', 'yellow', 'orange', 'white') print(colorsTuple[1:4])

Ijade:


('green', 'blue', 'yellow')

Atọka odi

A le wọle si awọn ohun kan lori tuple lati opin nipa sisọ iye itọka odi kan. Fun apẹẹrẹ -1 tumọ si ohun ti o kẹhin ati -2 tumo si ohun keji ti o kẹhin.

colorsTuple = ('red', 'green', 'blue', 'yellow', 'orange', 'white') print(colorsTuple[-2])

Ijade:

orange

Bii o ṣe le Loop Nipasẹ Tuple kan

A le lo nipasẹ tuple kan nipa lilo awọn for lupu.

colorsTuple = ('red', 'green', 'blue', 'orange') for c in colorsTuple:
print(c)

Ijade:


red green blue orange

Bii o ṣe le Pa Tuple rẹ kuro

Lati pa tuple patapata, lo del koko

colorsTuple = ('red', 'green', 'blue', 'orange') del colorsTuple print(colorsTuple)

Ijade

Traceback (most recent call last): File 'pythonTuples.py', line 98, in
print(colorsTuple) NameError: name 'colorsTuple' is not defined


Bii o ṣe le Gba gigun ti Tuple kan

O le gba ipari tuple nipasẹ pipe si len() iṣẹ, fun apẹẹrẹ:

colorsTuple = ('red', 'green', 'blue', 'orange') print(len(colorsTuple))

Ijade:


4

Nọmba Nọmba ti Awọn ohun kan ti a Ti Pato

A le lo awọn count() sisẹ lori awọn tuples lati gba nọmba awọn aṣiri ti nkan pàtó kan ninu tuple. Fun apere:

colorsTuple = ('red', 'green', 'blue', 'orange', 'red') print(colorsTuple.count('red'))

Ijade:

2

Bii O ṣe le Darapọ mọ Awọn Tuples Meji Paapọ

Ọna to rọọrun lati darapọ mọ awọn tuples meji papọ ni lati lo + onišẹ. Fun apere:

colorsTuple = ('red', 'green', 'blue', 'orange') numbersTuple = (1, 2, 3, 4) numbersAndColors = colorsTuple + numbersTuple print(numbersAndColors)

Ijade:


('red', 'green', 'blue', 'orange', 1, 2, 3, 4)