想要熟練掌握Python元組?你需要了解這10件應知事項
本文轉載自公眾號“讀芯術”(ID:AI_Discovery)
人生苦短,Python是岸。
作為一種通用編程語言,Python已成為各學術和工業(yè)領域中最流行的語言之一。
此前,IEEESpectrum 發(fā)布的第五屆年度編程語言交互排行榜中,Python 不但雄踞第一,在綜合指數(shù)、用戶增速、就業(yè)優(yōu)勢和開源語言單項中,全部霸占榜首。
Python擁有強大的數(shù)據(jù)結構集合,例如int、 string、 list、 dict和 tuple——一個大小固定且不可變數(shù)據(jù)序列。
在今天的文章里,小芯將帶領大家回顧正確使用Python元組的最常用方法。
1. 使用索引訪問元組中的單個元素
創(chuàng)建元組后,有時需要訪問它的一些值。一種方法是使用基于0的索引對其進行訪問。參見下方示例。值得注意的是,在Python中,使用負數(shù)以相反的順序索引序列。例如,-1是序列中最后一個元素的索引。當然,如試圖使用范圍之外的索引訪問元素,將看到IndexError(索引錯誤)。
- >>> tuple_index = (100,'text', False, {1: 'five', 2: True})>>> tuple_index[0]
- 100>>> tuple_index[-1]
- {1: 'five', 2: True}>>> tuple_index[2]
- False>>> tuple_index[6]
- Traceback (most recent call last):
- File "<stdin>", line 1,in <module>
- IndexError: tuple index out of range
2. 可變元素
雖然一個元組不能作為一個對象整體改變,但如果單個元素本身是可變的,就可以對其進行更改。參見下方示例。具體來說,修改了tuple(元組)中的 list 和 dict.
- >>> mutable_elements =(1, [1, 2], {0: 'zero', 1: 'one'})>>> mutable_elements[1].append(3)
- >>> mutable_elements
- (1, [1, 2, 3], {0: 'zero', 1: 'one'})>>> mutable_elements[2][2] ='two'
- >>> mutable_elements
- (1, [1, 2, 3], {0: 'zero', 1: 'one', 2: 'two'})
3. 高級元組拆包
有時拆包一個元組,并不需要訪問所有的單個元素。對于那些不重要的元素,可以用下劃線(_)表示。另一種高級的tuple (元組)拆包技術是,使用星號(*)表示tuple (元組)中的元素序列。_和*用法也可以組合使用。
- >>> advanced_unpacking0= (1, 2, 3)
- >>> a, _, c = advanced_unpacking0
- >>> a
- 1
- >>> c
- 3>>> advanced_unpacking1 = (1, 2, 3, 4, 5, 11, 12, 13, 14, 15)
- >>> a, *middle, c = advanced_unpacking1
- >>> middle
- [2, 3, 4, 5, 11, 12, 13, 14]
- >>> _, *tail = advanced_unpacking1
- >>> tail
- [2, 3, 4, 5, 11, 12, 13, 14, 15]
- >>> head, *_ = advanced_unpacking1
- >>> head
- 1
4. 使用值序列創(chuàng)建元組
創(chuàng)建元組時,需使用逗號分隔值序列。括號是可選的,尤其在聲明表達式不直接的情況下,使用括號可以提高可讀性。
- >>> tuple0 = 1, 4, 5
- >>> print(tuple0)
- (1, 4, 5)>>> tuple1 = (1, 2, 'three')
- >>> print(tuple1)
- (1, 2, 'three')>>> tuple2 = (4, 7, ('a', 'b'), lambda x: x+1)
- >>> print(tuple2)
- (4, 7, ('a', 'b'), <function <lambda> at 0x106e98830>)>>>tuple3 = ()
- >>> print(tuple3)
- ()>>> tuple4 = 'one',
- >>> print(tuple4)
- ('one',)
特殊的情況是:使用一對括號創(chuàng)建一個空tuple(元組);在唯一值后使用逗號創(chuàng)建單值tuple(元組)。
5. 計算元組中元素的數(shù)量
由于tuple(元組)是一個序列,所以可使用len()函數(shù)計算所有元素總數(shù)。另一個函數(shù) count()也很方便,可用做計算調(diào)用時指定的某個值的個數(shù)。參見下方示例。
- >>> tuple_len = (1, 3,'one', 'three', 'five')
- >>> len(tuple_len)
- 5>>> tuple_count = (1, 1, 2, 2, 2, 2, 3, 3, 3)
- >>> tuple_count.count(2)
- 4
- >>> tuple_count.count(3)
- 3
6. 使用tuple()函數(shù)創(chuàng)建元組
可使用內(nèi)置 tuple()方法創(chuàng)建元組,該方法將 iterable (迭代)作為唯一參數(shù)。生成的tuple (元組)將是 iterable 的迭代項序列。如下示例中,元組分別從str、dict和 list生成。
- >>> tupletuple5 =tuple(['a', 'b'])
- >>> print(tuple5)
- ('a', 'b')>>> tupletuple6 = tuple('tuple')
- >>> print(tuple6)
- ('t', 'u', 'p', 'l', 'e')>>> tupletuple7 = tuple({'a': 1, True: 4})
- >>> print(tuple7)
- ('a', True)>>> tupletuple8 = tuple((1, 'two', [1, 2]))
- >>> print(tuple8)
- (1, 'two', [1, 2])
7. 使用拆包方法訪問元組的單個元素
使用元組可能經(jīng)常聽到的另一個概念是tuple(元組)拆包,它允許訪問單個元素。參見下方示例。
- >>> tuple_unpacking =(1, 'two', [3, 3, 3], {'four': 4})
- >>> a, b, c, d = tuple_unpacking>>> a
- 1
- >>> b
- 'two'
- >>> c
- [3, 3, 3]
- >>> d
- {'four': 4}
8. for循環(huán)中的元組
時常需要在for循環(huán)中使用元組。由于元組是可迭代的,所以可直接在for循環(huán)中使用,該循環(huán)將迭代元組的單個元素?;蛘?,如果想應用計數(shù)器,可使用元組內(nèi)置的 enumerate() 方法。參見下方示例。
- >>> tuple_for_loop =('one', 'two', 'three')
- >>> for i in tuple_for_loop:
- ... print(i)
- ...
- one
- two
- three>>> for (i, item) in enumerate(tuple_for_loop, start=1):
- ... print(str(i) + ': is ' + item)
- ...
- 1: is one
- 2: is two
- 3: is three
9. 元組的不可變性
正如本文開頭提到的,元組是一個不可變值序列。因此,不能改變單個元素的值。
- >>> immut_tuple = (3,5, 7)
- >>> immut_tuple[0] = 1
- Traceback (most recent call last):
- File "<stdin>", line 1,in <module>
- TypeError: 'tuple' object does not support item assignment
10. 元組連接
可使用加號(+)運算符連接多個元組,來創(chuàng)建一個新元組?;蛘?,如果想通過多次連接同一元組來創(chuàng)建一個新的元組,可使用乘法(*)運算符。
- >>> concat_tuple0 = (1,2) + ('three', 4) + ('five', 6)
- >>> concat_tuple0
- (1, 2, 'three', 4, 'five', 6)>>> concat_tuple1 = ('odd', 'event') * 4
- >>> concat_tuple1
- ('odd', 'event', 'odd', 'event', 'odd', 'event', 'odd', 'event')
元組是筆者在Python編程中最喜歡使用的數(shù)據(jù)結構之一,因其便于構造和訪問單個元素。當然,請記住元組是不可變的,并且沒有過多的方法,這可能限制其更廣泛的使用,這種情況下,可以考慮使用list 或dict。