python之元组

时间:2024-10-16 05:37:09

1、定义一个元组:例如:In [77]: tupe=(12,33,23.32,"zhang","qing")In [78]: tupeOut[78]: (12, 33, 23.32, 'zhang', 'qing')In [79]: tupe1=(12,(12,34),"zhang")In [80]: tupe1Out[80]: (12, (12, 34), 'zhang')In [81]: tupe2=("zhang",[12,34,"zhang"],23)In [82]: tupe2Out[82]: ('zhang', [12, 34, 'zhang'], 23)In [83]: tupe3=('zhang',{"name":"zhang"},12)In [84]: tupe3Out[84]: ('zhang', {'name': 'zhang'}, 12)

python之元组

2、访问元组(一):In [85]: tupeOut[85]: (12, 33, 23.32, 'zhang', 'qing')In [86]: tupe[0]Out[86]: 12In [87]: tupe[1]Out[87]: 33In [88]: tupe[2]Out[88]: 23.32In [89]: tupe[3]Out[89]: 'zhang'In [90]: tupe[1,3]---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-90-3f0c13dc8437> in <module>()----> 1 tupe[1,3]TypeError: tuple indices must be integers or slices, not tupleIn [91]: tupe[1:3]Out[91]: (33, 23.32)

python之元组

3、访问元组(二):In [92]: tupe1Out[92]: (12, (12, 34), 'zhang')In [93]: tupe1[0]Out[93]: 12In [94]: tupe1[1]Out[94]: (12, 34)In [95]: tupe1[2]Out[95]: 'zhang'In [96]: tupe1[1][1]Out[96]: 34In [97]: tupe1[1][0]Out[97]: 12

python之元组

4、修改元组:注意:不能对元组进行修改In [98]: tupeOut[98]: (12, 33, 23.32, 'zhang', 'qing')In [99]: tupe[1]Out[99]: 33In [100]: tupe[1]=123---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-100-d8823ba5f314> in <module>()----> 1 tupe[1]=123TypeError: 'tuple' object does not support item assignmentIn [101]: tupe[1]="zhang"---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-101-7e6f9e95e567> in <module>()----> 1 tupe[1]="zhang"TypeError: 'tuple' object does not support item assignment

python之元组

5、元组内置函数之count:count 与字符串和列表中的用法相同例如:In [102]: tupeOut[102]: (12, 33, 23.32, 'zhang', 'qing')In [103]: tupe.index(12)Out[103]: 0In [104]: tupe.index(33)Out[104]: 1In [105]: tupe.index(3)---------------------------------------------------------------------------ValueError Traceback (most recent call last)<ipython-input-105-0a22a2aab0ff> in <module>()----> 1 tupe.index(3)ValueError: tuple.index(x): x not in tupleIn [106]: tupe.index('zhang',0,4)Out[106]: 3In [107]: tupe.index('zhang',0,3)---------------------------------------------------------------------------ValueError Traceback (most recent call last)<ipython-input-107-19c37b0692f1> in <module>()----> 1 tupe.index('zhang',0,3)ValueError: tuple.index(x): x not in tuple

python之元组

6、元组的内置函数之indexindex与字符串和列表中的用法相同例如:In [110]: tupeOut[110]: (12, 33, 23.32, 'zhang', 'qing')In [111]: tupe.count("zhang")Out[111]: 1In [112]: tupe.count("qing")Out[112]: 1In [113]: tupe.count(12)Out[113]: 1

python之元组
© 手抄报圈