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

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

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

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

1.列表(List)

元組是由一對方括號構(gòu)成的序列。列表創(chuàng)建后,可以根據(jù)自己的需要改變他的內(nèi)容

>>> list=[1,2,3,4,5,6]
>>> list[0]=8
>>> list[6]=0
>>> list
[8, 2, 3, 4, 5, 6]

可以為列表添加新的數(shù)據(jù):

>>> len(list) #查看這個列表中有多少數(shù)據(jù)
6
>>> list.append(7) #在列表尾插入
>>> list
[8, 2, 3, 4, 5, 6, 7]
>>> len(list)
7
>>> list.insert(3,10) ?#在列表任意位置插入數(shù)據(jù),第一個參數(shù)表示索引,第二個參數(shù)表示插入的數(shù)據(jù)
>>> list
[8, 2, 3, 10, 4, 5, 6, 7]
>>>?

2.元組(Tuple)

元組是由一對圓括號構(gòu)成的序列。元組創(chuàng)建后,不允許更改,即他的內(nèi)容無法被修改,大小也無法改變。

>>> 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進(jìn)行合并。

>>> t=(5,6,8,6)
>>> t+tuple
(5, 6, 8, 6, 1, 2, 3, 4)

元組中的值雖然不允許直接更改,但我們可以利用列表來改變元組中的值,可以使用函數(shù)list()將元組變?yōu)榱斜恚褂煤瘮?shù)tuple()將列表轉(zhuǎn)換為元組。

?>>>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關(guān)鍵詞,使用函數(shù)index()能夠返回查找到的值在元組中的索引。

n=103
if n in t:#在元組t中查找103
? ? indexn = t.index(n)#查找值在元組中的索引值(從0開始算)
print(indexn)

輸出結(jié)果:

1

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

輸出結(jié)果:

2

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

欄目分類
最近更新