內(nèi)建序列函數(shù)

1、 enumerate

目的:遍歷一個(gè)序列同時(shí)跟蹤當(dāng)前元素索引。

Python中內(nèi)建函數(shù)enumerate,返回(i, value)元組序列,其中i是元素的索引,value是元素的值。

In [4]: some_list = ['foo', 'bar', 'baz']

In [5]: mapping = {}

In [6]:  for i,v in enumerate(some_list):
   ...:      mapping[v] = i
   ...:

In [7]: mapping
Out[7]: {'foo': 0, 'bar': 1, 'baz': 2}

2、sorted

sorted 函數(shù)返回一個(gè)根據(jù)任意序列中元素新建的已排序的列表。

In [8]: sorted([7, 1, 2, 6, 0, 3, 2])
Out[8]: [0, 1, 2, 2, 3, 6, 7]

In [9]: sorted('horse race')
Out[9]: [' ', 'a', 'c', 'e', 'e', 'h', 'o', 'r', 'r', 's']

3、zip

zip 將列表、元組或其它序列的元素配對(duì),新建一個(gè)元組構(gòu)成的列表。

In [10]: seq1 = ['foo', 'bar', 'baz']

In [11]: seq2 = ['one', 'two', 'three']

In [12]: zipped = zip(seq1, seq2)

In [13]: list(zipped)
Out[13]: [('foo', 'one'), ('bar', 'two'), ('baz', 'three')]

In [14]: seq3 = [False, True]

In [15]: list(zip(seq1, seq2, seq3))
Out[15]: [('foo', 'one', False), ('bar', 'two', True)]

zip 常用場(chǎng)景為同時(shí)遍歷多個(gè)序列,會(huì)和 enumerate 同時(shí)使用。

In [17]: for i, (a, b) in enumerate(zip(seq1, seq2)):
    ...:     print('{0}: {1}, {2}'.format(i, a, b))
    ...:
0: foo, one
1: bar, two
2: baz, three

給定一個(gè)配對(duì)的序列,zip 函數(shù)可將其拆分。

In [18]: pitchers = [('Nolan', 'Ruan'), ('Roger', 'Clemens'),
    ...: ('Schilling', 'Curt')]

In [19]: first_names, last_names = zip(*pitchers)

In [20]: first_names
Out[20]: ('Nolan', 'Roger', 'Schilling')

In [21]: last_names
Out[21]: ('Ruan', 'Clemens', 'Curt')

4、reversed

reversed 函數(shù)將序列的元素倒序排列。

In [22]: list(reversed(range(10)))
Out[22]: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容