简体   繁体   English

如何构造所有可能组合的元组列表

[英]How to construct a list of tuples of all possible combinations

I just can't come up with a way to solve my problem: x is an integer. 我只是想不出办法解决我的问题:x是整数。 I want a list of all possibles combinations of x-tuples where those tuples' elements are in range from 0 to x (excluding x). 我想要一个x元组的所有可能组合的列表,其中那些元组的元素的范围是0到x(不包括x)。

So if x = 3 I have 3^3 combinations: [(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)] . 因此,如果x = 3我有3 ^ 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)]

If x = 4 I would have 4^4 combinations with 4-tuples where the elements of those tuples are in {0,1,2,3}. 如果x = 4我将具有4元组的4 ^ 4组合,其中这些元组的元素在{0,1,2,3}中。

Here's the proper way to use itertools to get what you want: 这是使用itertools获得所需内容的正确方法:

list(itertools.product(range(3), repeat=3))

The output is: 输出为:

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

Of course, this can scale up by using values other than 3. In general: 当然,可以使用3以外的其他值来扩大规模。通常:

list(itertools.product(range(x), repeat=x))

will work for any x . 将适用于任何x

I think it's just a list comprehension: 我认为这只是列表理解:

mylist = [(x,y,z) for x in range(3) for y in range(3) for z in range(3)]

Note that using itertools.permutations(range(3)) doesn't generate duplicates, just the permutations of the set (0, 1, 2). 请注意,使用itertools.permutations(range(3))不会生成重复项,而只会生成集合(0,1,2)的排列。 Ie you won't get (1, 1, 2), etc. 也就是说,您不会得到(1、1、2)等。

Ok, not permatations, but permutations with repeats perhaps. 好的,不是排列,而是重复排列。
Anyway, itertools.product() is doing that: 无论如何, itertools.product()正在这样做:

list(itertools.product([0,1,2],repeats=3))

result: 结果:

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

oh it's a dupe. 哦,这是骗子。 But I found it too :-) 但我也找到了它:-)

(Side remark: combinations are about subsets, and thus order of elements does not matter to them) (旁注: 组合是关于子集的,因此元素的顺序对它们无关紧要)

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

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