前戏
#元祖:元素不可被改变,不能白增加或者删除#tuple#tu = (11,22,33,44)#tu.count(22),获取指定元素在元祖中出现的次数#tu.index(22),获取元素的下标
• 不能增加或者删除元素
1、书写格式
tu = (111,"alex",(11,22),[(33,44)],True,33,44,)print(tu)结果:(111, 'alex', (11, 22), [(33, 44)], True, 33, 44)# 一般写元组的时候,推荐在最后加入 ,# 元素不可被修改,不能被增加或者删除
2、索引
tu = (111,"alex",(11,22),[(33,44)],True,33,44,)print(tu[1])结果:alex
3、切片
tu = (111,"alex",(11,22),[(33,44)],True,33,44,)print(tu[1:3])结果:('alex', (11, 22))#>=1 <3
4、可以被for循环,可迭代对象
tu = (111,"alex",(11,22),[(33,44)],True,33,44,)for i in tu: print(i)结果:111alex(11, 22)[(33, 44)]True3344
5、转换
s = "charon"li = ["charon","pluto"]tu = ("pluto","charon",)v = tuple(s)print(v)v1 = tuple(li)print(v1)v2 = list(tu)print(v2)v3 = "_".join(tu)print(v3)li.extend((11,22,33,))print(li)v4 = li.pop()print(v4)结果:('c', 'h', 'a', 'r', 'o', 'n')('charon', 'pluto')['pluto', 'charon']pluto_charon['charon', 'pluto', 11, 22, 33]33
6、元祖的一级元素不可修改,删除,增加
tu = (111,"alex",(11,22),[(33,44)],True,33,44,)v = tu[3][0]print(v)tu[3][0] = 2print(tu)结果:(33, 44)(111, 'alex', (11, 22), [2], True, 33, 44)#元祖不可以更改,但是元祖里面的列表是可以更改的