首页 > 编程语言 > 详细

Python Tuple元组的操作说明

时间:2017-12-30 11:53:56      阅读:227      评论:0      收藏:0      [点我收藏+]

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

 

Python Tuple元组的操作说明

原文:https://www.cnblogs.com/rhyswang/p/8148410.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!