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.
colorsTuple = ('red', 'green', 'blue') print(colorsTuple)
Ijade:
('red', 'green', 'blue')
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',)
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
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šẹ.
colorsTuple = ('red', 'green', 'blue', 'yellow', 'orange', 'white') print(colorsTuple[1:4])
Ijade:
('green', 'blue', 'yellow')
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
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
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
O le gba ipari tuple nipasẹ pipe si len()
iṣẹ, fun apẹẹrẹ:
colorsTuple = ('red', 'green', 'blue', 'orange') print(len(colorsTuple))
Ijade:
4
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
Ọ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)