正文
from
itertools
import
chain
>>>
>>>
string
=
chain
.
from_iterable
(
'ABCD'
)
>>>
string
.
next
()
'A'
compress
compress
的使用形式如下:
compress(data, selectors)
compress
可用于对数据进行筛选,当 selectors 的某个元素为 true 时,则保留 data 对应位置的元素,否则去除:
>>> from itertools import compress
>>>
>>> list(compress('ABCDEF', [1, 1, 0, 1, 0, 1]))
['A', 'B', 'D', 'F']
>>> list(compress('ABCDEF', [1, 1, 0, 1]))
['A', 'B', 'D']
>>> list(compress('ABCDEF', [True, False, True]))
['A', 'C']
dropwhile
dropwhile
的使用形式如下:
dropwhile(predicate, iterable)
其中, predicate 是函数, iterable 是可迭代对象。对于 iterable 中的元素,如果 predicate(item)为 true ,则丢弃该元素,否则返回该项及所有后续项。
>>> from itertools import dropwhile
>>>
>>> list(dropwhile(lambda x: x 5, [1, 3, 6, 2, 1]))
[6, 2, 1]
>>>
>>> list(dropwhile(lambda x: x > 3, [2, 1, 6, 5, 4]))
[2, 1, 6, 5, 4]
groupby
groupby
用于对序列进行分组,它的使用形式如下:
groupby(iterable[, keyfunc])
其中, iterable 是一个可迭代对象, keyfunc 是分组函数,用于对 iterable 的连续项进行分组,如果不指定,则默认对 iterable 中的连续相同项进行分组,返回一个
(
key
,
sub
-
iterator
)
的迭代器。
>>> from itertools import groupby
>>>
>>> for key, value_iter in groupby('aaabbbaaccd'):
... print key, ':', list(value_iter)
...
a:
['a', 'a', 'a']
b:
['b', 'b', 'b']
a:
['a', 'a']
c:
['c', 'c']
d:
['d']
>>>
>>> data = ['a', 'bb', 'ccc', 'dd', 'eee', 'f']
>>> for key, value_iter in groupby(data, len): # 使用 len 函数作为分组函数
... print key, ':', list(value_iter)
...
1:
['a']
2:
['bb']
3:
['ccc']
2:
['dd']
3:
['eee']
1:
['f']
>>>
>>> data = ['a', 'bb', 'cc', 'ddd', 'eee', 'f']
>>> for key, value_iter in groupby(data, len):
... print key, ':', list(value_iter)
...