1.列表(List)
元组是由一对方括号构成的序列。列表创建后,可以根据自己的需要改变他的内容
>>> list=[1,2,3,4,5,6] >>> list[0]=8 >>> list[6]=0 >>> list [8, 2, 3, 4, 5, 6]
可以为列表添加新的数据:
>>> len(list) #查看这个列表中有多少数据 6 >>> list.append(7) #在列表尾插入 >>> list [8, 2, 3, 4, 5, 6, 7] >>> len(list) 7 >>> list.insert(3,10) ?#在列表任意位置插入数据,第一个参数表示索引,第二个参数表示插入的数据 >>> list [8, 2, 3, 10, 4, 5, 6, 7] >>>?
2.元组(Tuple)
元组是由一对圆括号构成的序列。元组创建后,不允许更改,即他的内容无法被修改,大小也无法改变。
>>> tuple=(1,2,3,4) >>> tuple (1, 2, 3, 4) >>> tuple[2] 3 >>> tuple[2]=8 Traceback (most recent call last): ? File "<pyshell#13>", line 1, in <module> ? ? tuple[2]=8 TypeError: 'tuple' object does not support item assignment
虽然元组不支持改变大小,但可以将两个 tuple 进行合并。
>>> t=(5,6,8,6) >>> t+tuple (5, 6, 8, 6, 1, 2, 3, 4)
元组中的值虽然不允许直接更改,但我们可以利用列表来改变元组中的值,可以使用函数 list() 将元组变为列表,使用函数tuple()将列表转换为元组。
?>>>t=(5631,103,"Finn","Bilous","Wanaka","1999-09-22") ?>>> print (t) ?(5631,103,"Finn","Bilous","Wanaka","1999-09-22") ?>>>lst = list(t) ?>>>print (lst) ?[5631,103,"Finn","Bilous","Wanaka","1999-09-22"] ?>>>lst[4] = 'LA' ?>>>t= tuple(lst) ?>>>print(t) ?(5631,103,"Finn","Bilous","LA","1999-09-22")
在元组中查找指定值可以使用in关键词,使用函数 index() 能够返回查找到的值在元组中的索引。
n=103 if n in t:#在元组t中查找103 ? ? indexn = t.index(n)#查找值在元组中的索引值(从0开始算) print(indexn)
输出结果:
n="Finn" if n in t: ? ? indexn = t.index(n) print(indexn)输出结果:
到此这篇关于python中的元组与列表及元组的更改的文章就介绍到这了,更多相关python元组与列表内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
查看更多关于python中的元组与列表及元组的更改的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did99268