python-----元组

元组

元组与列表相似,不同之处在于元组的元素不能修改。可进行分片和连接操作。
元组使用小括号(),列表使用方括号[]

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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值