说我有3个参数:范围,n个元素元组的大小(实际上也可能是一个列表)和可能的组合(无重复)。我想从范围中获取所有可能的数字组合。
例如:
无重复
结果将是:
(1,1)(1,2)(1,3)(1,4)(1,5) (2,1)(2,2)(2,3)(2,4)(2,5) (3,1)(3,2)(3,3)(3,4)(3,5) (4,1)(4,2)(4,3)(4,4)(4,5) (5,1)(5,2)(5,3)(5,4)(5,5)
随着重复的进行,当然会有更多的元组。
很明显,它可以迭代完成,但是实现此任务的更加Python化和优雅的方式(也许是其他工具)又会是什么呢?
答案 0 :(得分:4)
带有重复:
>>> from itertools import product
>>> list(product(range(1, 6), repeat=2))
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5)]
无重复:
>>> from itertools import permutations
>>> list(permutations(range(1, 6), 2))
[(1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4)]