原文:https://diveintopython3.net/advanced-iterators.html
>>> import itertools
>>> perms = itertools.permutations([1, 2, 3], 2)
>>> next(perms)
(1, 2)
>>> next(perms)
(1, 3)
>>> next(perms)
(2, 1)
>>> next(perms)
(2, 3)
>>> next(perms)
(3, 1)
>>> next(perms)
(3, 2)
>>> next(perms)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> import itertools
>>> list(itertools.product('ABC', '123'))
[(''A' ,'1' ),('A' ,'2' ),('A' ,'3' ),('B' ,'1' ),('B' ,'2' ) ,('B' ,'3' ),('C' ,'1' ),('C' ,'2' ),('C' ,'3' )]
>>> list(itertools.combinations('ABC', 2))
[(('A' ,'B' ),('A' ,'C' ),('B' ,'C' )]
根据列表的值长度,判断数量【没有去重功能】
import itertools
names=['Alex', 'Anne', 'Dora', 'John', 'Mike','Chris', 'Ethan', 'Sarah', 'Lizzie', 'Wesley']
groups = itertools.groupby(names, len)
print(groups)
# <itertools.groupby object at 0x00000207D3702040>
print(list(groups))
# [(4, <itertools._grouper object at 0x00000207D3778070>), (5, <itertools._grouper object at 0x00000207D3778550>), (6, <itertools._grouper object at 0x00000207D541FFD0>)]
groups = itertools.groupby(names, len)
for name_length, name_iter in groups:
print('Names with {0:d} letters:'.format(name_length))
for name in name_iter:
print(name)
'''
Names with 4 letters:
Alex
Anne
Dora
John
Mike
Names with 5 letters:
Chris
Ethan
Sarah
Names with 6 letters:
Lizzie
Wesley
'''
>>> list(range(0, 3))
[0, 1, 2]
>>> list(range(10, 13))
[10, 11, 12]
>>> list(itertools.chain(range(0, 3), range(10, 13)))
[0, 1, 2, 10, 11, 12]
>>> list(zip(range(0, 3), range(10, 13)))
[(0, 10), (1, 11), (2, 12)]
>>> list(zip(range(0, 3), range(10, 14)))
[(0, 10), (1, 11), (2, 12)]
>>> list(itertools.zip_longest(range(0, 3), range(10, 14)))
[(0, 10), (1, 11), (2, 12), (None, 13)]
博客提及根据列表的值长度判断数量,且无去重功能,还给出原文链接https://diveintopython3.net/advanced-iterators.html 。
324





