简体   繁体   English

对于给定的值范围,生成给定大小的所有可能的元组组合

[英]Generate all possible tuples combinations of given size for given range of values

Say I have 3 parameters: a range, size of n-element tuples (actually it might also be a list) and possible combinations (without or with repetition). 假设我有3个参数:范围,n元素元组的大小(实际上也可能是列表)和可能的组合(无重复)。 I want to get all the possible combinations of the numbers from the range. 我想从范围中获取所有可能的数字组合。

So for example: 因此,例如:

  • Range a..b = 1..5 范围a..b = 1..5
  • size of tuple s=2 元组的大小s = 2
  • without repetitions 没有重复

    the result would be: 结果将是:

    (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) (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)

With repetitions there would be of course much more tuples. 有了重复,当然会有更多的元组。

It can be done iteratively obviously, but what would be the more pythonic and elegant way of achieving this task (maybe additional tools)? 显然,它可以迭代地完成,但是实现此任务的更加Python化和优雅的方式(也许是其他工具)将是什么?

With repetitions: 重复:

>>> 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)]

Without repetitions: 无重复:

>>> 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)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM