python中的元组
元组
1.元组与列表类似,里面的元素用","号隔开,使用小括号
2.元组里面的数据不可修改
tuple = (1,2,3,4,'b')
修改元组中的元素,不可修改
tuple = (1,2,3,4,'b') tuple[0]=0 print(tuple) 结果: Traceback (most recent call last): File "/Users/mahong/Desktop/study/Auto_Python/day2/元组.py", line 11, in <module> tuple[0]=0 TypeError: 'tuple' object does not support item assignment
当元组中只有一个元素时,需要在后面加上逗号',',否则会被当成运算符使用
tuple1 = (1) print(type(tuple1)) tuple2 = (1,) print(type(tuple2)) 输出: <class 'int'> <class 'tuple'>
访问元组,同样遵循顾头不顾尾的规则
tuple = (1,2,3,4,'b') print(tuple[1:3]) 输出: (2, 3)
删除元组,不能删除元组中的元素,只能删除整个元组
tp = (1,2,3,4,'b') print(tp) del tp print(tp) 输出: (1, 2, 3, 4, 'b') Traceback (most recent call last): File "/Users/mahong/Desktop/study/Auto_Python/day2/元组.py", line 13, in <module> print(tp) NameError: name 'tp' is not defined
内置方法:len(tuple),列表转元组tuple(list)
tp = (1,2,3,4,'b') print(len(tp)) L1 = ['a','b','c','d','e'] tuple(L1) print(tuple(L1)) 输出: 5 ('a', 'b', 'c', 'd', 'e')