Python:itertools模块 combinations和product的使用
2018-02-07 22:55
876 查看
1.combinations(iterable, r) 创建一个迭代器,返回iterable中所有长度为r的子序列,返回的子序列中的项按输入iterable中的顺序排序:官方文档
例:
2.product(*iterables[, repeat]) 创建一个迭代器,生成表示iterables中的项目的笛卡尔积的元组,repeat表示重复生成序列的次数。
例:
转载于:https://www.cnblogs.com/yu-zhang/p/3556232.html
def combinations(iterable, r): pool = tuple(iterable) n = len(pool) for indices in permutations(range(n), r): if sorted(indices) == list(indices): yield tuple(pool[i] for i in indices)
例:
>>> list(combinations(range(3),2)) [(0, 1), (0, 2), (1, 2)] >>> list(combinations(range(3),3)) [(0, 1, 2)] >>> list(combinations(range(3),1)) [(0,), (1,), (2,)]
2.product(*iterables[, repeat]) 创建一个迭代器,生成表示iterables中的项目的笛卡尔积的元组,repeat表示重复生成序列的次数。
def product(*args, **kwds): # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 pools = map(tuple, args) * kwds.get('repeat', 1) result = [[]] for pool in pools: result = [x+[y] for x in result for y in pool] for prod in result: yield tuple(prod)
例:
>>> list(product(range(3),repeat=1)) [(0,), (1,), (2,)] >>> list(product(range(3),repeat=2)) [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)] >>> list(product(range(3),repeat=3)) [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (0, 2, 1), (0, 2, 2), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 2, 0), (1, 2, 1), (1, 2, 2), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 2, 0), (2, 2, 1), (2, 2, 2)]
转载于:https://www.cnblogs.com/yu-zhang/p/3556232.html
相关文章推荐
- Python:itertools模块 combinations和product的使用
- [转]可爱的 Python:: 使用 itertools 模块中的组合函数
- Python 内置模块itertools的使用
- Python小技巧:使用*解包和itertools.product()求笛卡尔积
- Python小技巧:使用*解包和itertools.product()求笛卡尔积
- python高级编程-Part2 高效的迭代器模块itertools
- Python使用模块Pyserial模块报<ImportError:No module named tools.list_ports>
- Python:itertools模块-groupby
- python中itertools模块介绍---02
- python itertools模块
- python itertools的使用
- python itertools模块
- python模块之itertools
- python itertools的使用
- 粗谈Python内置库itertools-chain与combinations
- Python itertools的使用
- python内建模块之itertools
- Python中itertools模块
- Python学习笔记-4(模块:collections、itertools、xml)
- Python中itertools模块用法详解