日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python中的元組與列表及元組的更改_python

作者:m0_67392409 ? 更新時間: 2022-05-24 編程語言

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 "", line 1, in 
? ? 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)

輸出結果:

1

n="Finn"
if n in t:
? ? indexn = t.index(n)
print(indexn)

輸出結果:

2

原文鏈接:https://blog.csdn.net/m0_67392409/article/details/123629081

欄目分類
最近更新