How to create N-tuples in Python?

心已入冬 提交于 2019-12-22 18:30:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!