元组
元组与列表相似,不同之处在于元组的元素不能修改。可进行分片和连接操作。
元组使用小括号(),列表使用方括号[]
1访问元组
tuple=("hello",100,200)
a=tuple[0]
a1=tuple[1]
print(a)
print(a1)
运行结果:hello
100
2修改元组
tuple=("hello",100,200)
tuple[1]=222
a2=tuple[1]
print(a2)
运行结果: 报错!!!
tuple[1]=222
TypeError: 'tuple' object does not support item assignment
说明元组元素不可改
3合并成一个新元组
tuple1=("hello",100,200)
tuple2=("world",234)
tuple=tuple1+tuple2
print(tuple)
运行结果:('hello', 100, 200, 'world', 234)
4删除元素
元组中的元素值不允许删除,但是可以使用del删除整个元组
tuple=("hello",100,200)
del tuple
print(tuple)
运行结果:<type 'tuple'>
5元组运算符
与字符串相同,元组之间可以使用+和*运算。这意味着他们可以组合和复制,运算后会生成一个新的元组。
6元组索引、截取
因为元组也是一个序列,所以可以访问元组中的指定位置元素,也可截取索引中的一部分元素
L=(“spam”,”spam”,”SPAM!”)
7元组内置函数
8多维访问
tuple=(("hello",100,200),("world",233,"you"))
a=tuple[1][1]
b=tuple[0][0]
c=tuple[1][2]
print(a)
print(b)
print(c)
运行结果:233
hello
you
另:访问超出索引值的会报错!!!
tuple=(("hello",100,200),("world",233,"you"))
c=tuple[1][3]
print(c)
运行结果:
c=tuple[1][3]
IndexError: tuple index out of range