Python Tuple元组的操作说明

Tuple的特性在于,它的元素是不可变的(immutable),一旦设定,就不能使用索引去修改。

>>> t1=1,2,3,4,5 #给Tuple赋值
>>> t1[0] #按照索引读取Tuple元素
1
>>> u1=t1,(2,3,4,5,6)#tuple可以嵌套
>>> u1
((1, 2, 3, 4, 5), (2, 3, 4, 5, 6))
>>> u1[1]
(2, 3, 4, 5, 6)
>>> u1[-1]
(2, 3, 4, 5, 6)
>>> u1=t1,(2,3,4,5,6),3
>>> u1
((1, 2, 3, 4, 5), (2, 3, 4, 5, 6), 3)
>>> list1=['we','the','north']
>>> list1
['we', 'the', 'north']
>>> u1=t1,list1
>>> u1
((1, 2, 3, 4, 5), ['we', 'the', 'north'])
>>> list1[-1]='toronto'#元组内的元素是可变的,所以可以修改内部元素来更新元组
>>> u1
((1, 2, 3, 4, 5), ['we', 'the', 'toronto'])
>>> len(u1)
2
>>> myList = [1,2,3,4,5,6,7,8,9,10]
>>> myTuple = (1,2,3,4,5,6,7,8,9,10)
>>> myList=(2,)#初始化一个元素的时候,需要带comma
>>> myList
(2,)
>>> myList[0]
2
>>> myList[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>> len(myList)
1

 

转载于:https://www.cnblogs.com/rhyswang/p/8148410.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值