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
时间: 2024-10-03 05:02:09