1、 enumerate
目的:遍歷一個序列同時跟蹤當(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ù)返回一個根據(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 將列表物赶、元組或其它序列的元素配對,新建一個元組構(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 常用場景為同時遍歷多個序列块差,會和 enumerate 同時使用。
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
給定一個配對的序列倔丈,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]