如何在Python中创建N元组? [英] How to create N-tuples in Python?
本文介绍了如何在Python中创建N元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python中创建n元组列表的最简单方法是什么?
What would be the easiest way to create a list of n-tuples in Python?
例如,如果我要创建数字n(例如3):
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)
推荐答案
使用 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)]
这篇关于如何在Python中创建N元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文