简体   繁体   中英

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. I want a list of all possibles combinations of x-tuples where those tuples' elements are in range from 0 to x (excluding 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)] .

If x = 4 I would have 4^4 combinations with 4-tuples where the elements of those tuples are in {0,1,2,3}.

Here's the proper way to use itertools to get what you want:

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:

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

will work for any 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). Ie you won't get (1, 1, 2), etc.

Ok, not permatations, but permutations with repeats perhaps.
Anyway, itertools.product() is doing that:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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