问题
What would be the easiest way to create a list of n-tuples in Python?
For example, if I want to create for a number n (for e.g. 3):
I'd want to generate the following set of tuples:
(1,1,1) (1,1,2) (1,1,3) (2,1,1) (2,1,2) (2,1,3) (3,1,1) (3,1,2) (3,1,3)
(1,2,1) (1,2,2) (1,2,3) (2,2,1) (2,2,2) (2,2,3) (3,2,1) (3,2,2) (3,2,3)
(1,3,1) (1,3,2) (1,3,3) (2,3,1) (2,3,2) (2,3,3) (3,3,1) (3,3,2) (3,3,3)
回答1:
Use itertools.product:
>>> from itertools import product
>>> list(product(range(1, 4), repeat=3))
[(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 1), (1, 3, 2), (1, 3, 3), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 3, 1), (3, 3, 2), (3, 3, 3)]
回答2:
l = [1, 2, 3]
from itertools import product
print [item for item in product(l, repeat=3)]
回答3:
indeed itertools.product
acts like nested for-loops for its input iterables:
list((x,y,z) for x in range(1,4) for y in range(1,4) for z in range(1,4))
equivalent to:
list(product(range(1, 4), repeat=3))
# or
list(product(range(1, 4), range(1, 4), range(1, 4)))
来源:https://stackoverflow.com/questions/21208767/how-to-create-n-tuples-in-python