元組
元組:簡(jiǎn)單理解就是固定長(zhǎng)度游沿,不可變的列表
元組創(chuàng)建
元組的創(chuàng)建主要有如下幾種方式:
(1)逗號(hào)分隔:tup = 4,5,6
(2)圓括號(hào):tup = (4,5,6)
(3)利用任意的序列或者迭代器轉(zhuǎn)換成元組:tuple([1,2,3]); tuple('string')
tup1 = 4,5,6
tup2 = (7,8,9)
tup3 = tuple([1,2,3,4])
tup4 = tuple('hello world')
print(tup1, type(tup1))
print(tup2, type(tup2))
print(tup3, type(tup3))
print(tup4, type(tup4))
>>>(4, 5, 6) <class 'tuple'>
(7, 8, 9) <class 'tuple'>
(1, 2, 3, 4) <class 'tuple'>
('h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd') <class 'tuple'>
元組的索引
元組不能改變,因此它無法增肮砾、刪(刪除某一個(gè)元素)诀黍、改,但是它能夠查/被索引仗处,同時(shí)也能被整體刪除:
(1)通過索引來獲取元組中的元素:此時(shí)的返回值依然是一個(gè)元組
tup[:-1]
tup[1]
(2)刪除整個(gè)元組眯勾,使用del語句
del tup
tup = tuple('hello world')
print(tup[:-1])
print(tup[1])
del tup
print(tup)
>>>('h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l')
e
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-9-e2a83b3a252f> in <module>
4
5 del tup
----> 6 print(tup)
NameError: name 'tup' is not defined
元組的連接:
(1)通過使用'+'可以將多個(gè)元組進(jìn)行連接,最后會(huì)生成一個(gè)新的元組
(1,2,3)+tuple(['foo',[66,77]])+('string',1)
tup1 = (1,2,3)
tup2 = tuple(['foo',[66,77]])
tup3 = ('hello', 99)
res = tup1+tup2+tup3
print(res) >>>(1, 2, 3, 'foo', [66, 77], 'hello', 99)
元組的拷貝:
使用 * 可以進(jìn)行元組的拷貝婆誓,如下生成4分拷貝吃环,但是對(duì)象自身并沒有復(fù)制,而是生成了一個(gè)新的元組
('foo',2) * 4
tup = ('foo', 89.9, 90)
res = tup * 4
print(tup)
print(res)
----------------------------------------
('foo', 89.9, 90)
('foo', 89.9, 90, 'foo', 89.9, 90, 'foo', 89.9, 90, 'foo', 89.9, 90)
元組型表達(dá)式賦值給變量
這種方式常用在遍歷元組列表組成的序列中
tup=(4洋幻,5郁轻,6)
a, b, c = tup
高級(jí)用法:*rest
python增加了更為高級(jí)的元組拆包功能,用于從元組的起始位置采集一些元素鞋屈,這里主要關(guān)注兩個(gè)用法:
(1)*rest:用于在函數(shù)調(diào)用時(shí)獲取任意長(zhǎng)度的位置參數(shù)列表范咨,返回值是一個(gè)列表
(2)*_:如果rest是你不想要的數(shù)據(jù)故觅,那么可以使用*_表示。
values = 1,2,3,4,5
a, b, *rest = values
values = (1,2,3,4,5)
a, *rest, c = values
print(a, c)
print(type(rest))
print(rest)
---------------------------------------
1 5
<class 'list'>
[2, 3, 4]
元組的常用方法
(1)tuple.count(value):計(jì)算元組某個(gè)元素的個(gè)數(shù)
tup = (1,2,3,2,2,2,5,6)
tup.count(2)
>>>4
元組常用的內(nèi)置函數(shù)
tup = (1,2,3,2,2,2,5,6)
len(tup)
max(tup)
min(tup)
sum(tup)