说明:
tu=()
元组只有一个元素时,后面需要加逗号”,“,因为‘abc’等同于(‘abc‘),如
tupe1=(‘abc‘,)
tup1 = (‘physics‘, ‘chemistry‘, 1997, 2000) tup2 = (1, 2, 3, 4, 5, 6, 7 ) print ("tup1[0]: ", tup1[0]) print ("tup2[1:5]: ", tup2[1:5])
运行结果:
tup1[0]: physics
tup2[1:5]: (2, 3, 4, 5)
for遍历:
#遍历元组 zoo = (‘wolf‘, ‘elephant‘, ‘penguin‘) new_zoo = (‘monkey‘, ‘dolphin‘, zoo) for animal in zoo: print (animal) print (‘-‘*10) #遍历嵌套元组: for animal in new_zoo: if isinstance(animal,tuple): for newAnimal in animal: print (newAnimal) else: print (animal)
运行结果:
wolf
elephant
penguin
----------
monkey
dolphin
wolf
elephant
penguin
实例1:
tup1 = (12, 34.56) tup2 = (‘abc‘, ‘xyz‘) tup3 = (‘abc‘,[‘A‘,‘B‘,‘C‘]) # 以下修改元组元素操作是非法的,会报错 # tup1[0] = 100 # 创建一个新的元组 tup4 = tup1 + tup2 print (tup4) # 修改元组内的列表元素(list本身可变) tup3[1][0]=‘X‘ tup3[1][1]=‘Y‘ tup3[1][2]=‘Z‘ print (tup3)
运行结果:
(12, 34.56, ‘abc‘, ‘xyz‘)
(‘abc‘, [‘X‘, ‘Y‘, ‘Z‘])
如果需要对元组的元素进行添加、修改操作,对元组进行列表转换操作,再对列表类型的元素操作:list()
tup1 = (‘physics‘, ‘chemistry‘, 1997, [198,987,27], 2000) # 方法1: tup1[3].extend([123,12]) #extend(列表) print (tup1) # 方法2: tup1[3].append(123) #append(元素) tup1[3].append(12) print (tup1) #方法3: for i in tup1: if isinstance(i,list): i.extend([123,12]) print (tup1)
运行结果:
(‘physics‘, ‘chemistry‘, 1997, [198, 987, 27], 2000)
如下例子修改会报错:
tup = (‘physics‘, ‘chemistry‘, 1997, 2000); print (tup) del tup print ("After deleting tup : " ) print (tup)
运行结果:
(‘physics‘, ‘chemistry‘, 1997, 2000)
Traceback (most recent call last):
After deleting tup :
File "E:/workplace/2019pratice/practice1.py", line 227, in <module>
print (tup)
NameError: name ‘tup‘ is not defined
原文:https://www.cnblogs.com/wenxiacui/p/10964047.html