python中的元组与列表,合并、更改和返回索引值
转载声明:
本文为摘录自“csdn博客”,版权归原作者所有。
温馨提示:
为了更好的体验,请点击原文链接进行浏览
摘录时间:
2022-05-30 14:13:05
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) #在列表第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
3.元组的合并与更改,列表与元组的相互转换
虽然元组不支持改变大小,但可以将两个元组进行合并。
>>> 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")
4.查找元组中指定的值,并返回其在序列中的索引
在元组中查找指定值可以使用in关键词,
使用函数index()能够返回查找到的值在元组中的索引。
n=103
if n in t:#在元组t中查找103
indexn = t.index(n)#查找值在元组中的索引值(从0开始算)
print(indexn)
输出结果:1
n="Finn"
if n in t:
indexn = t.index(n)
print(indexn)
输出结果:2