今天看到一个创建列表组合很巧妙的方式。以下为摘抄的原文。
迭代工具模块包含了操做指定的函数用于操作迭代器。想复制一个迭代器出来?链接两个迭代器?以one liner(这里的one-liner只需一行代码能搞定的任务)用内嵌的列表组合一组值?不使用list创建Map/Zip?···,你要做的就是 import itertools,举个例子吧:
四匹马赛跑到达终点排名的所有可能性:
- >>> horses = [1, 2, 3, 4]
- >>> races = itertools.permutations(horses)
- >>> print(races)
- <itertools.permutations object at 0xb754f1dc>
- >>> print(list(itertools.permutations(horses)))
- [(1, 2, 3, 4),
- (1, 2, 4, 3),
- (1, 3, 2, 4),
- (1, 3, 4, 2),
- (1, 4, 2, 3),
- (1, 4, 3, 2),
- (2, 1, 3, 4),
- (2, 1, 4, 3),
- (2, 3, 1, 4),
- (2, 3, 4, 1),
- (2, 4, 1, 3),
- (2, 4, 3, 1),
- (3, 1, 2, 4),
- (3, 1, 4, 2),
- (3, 2, 1, 4),
- (3, 2, 4, 1),
- (3, 4, 1, 2),
- (3, 4, 2, 1),
- (4, 1, 2, 3),
- (4, 1, 3, 2),
- (4, 2, 1, 3),
- (4, 2, 3, 1),
- (4, 3, 1, 2),
- (4, 3, 2, 1)]