和collections库一样,还有一个库叫itertools,对某些问题真能高效地解决。其中一个用例是查找所有组合,他能告诉你在一个组中元素的所有可能的组合方式
- from itertools import combinations
- teams = ["a", "b", "c", "d"]
- for game in combinations(teams, 2):
- print game
- >>> ('a', 'b')
- >>> ('a', 'c')
- >>> ('a', 'd')
- >>> ('b', 'c')
- >>> ('b', 'd')
- >>> ('c', 'd')
复制代码
- >>> import itertools
- >>> list(itertools.combinations('abc', 2))
- [('a', 'b'), ('a', 'c'), ('b', 'c')]
- >>> list(itertools.permutations('abc',2))
- [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
- >>>
复制代码
[url=http://static.wooyun.org/upload/image/201507/2015072719173454967.jpg][/url]
|