我想创建一个包含三个值的数字列表,并希望覆盖0到3之间的每个组合。例如:
0, 0, 0
0, 0, 1
...
1, 0, 3
1, 1, 3
一直到3, 3, 3
。
有没有比使用多个for循环更好的方法呢?
以下是我使用的代码:
for i in range (0, 4):
for x in range (0, 4):
for t in range (0, 4):
assign = [i, x, t]
答案 0 :(得分:3)
list(itertools.product(range(4), repeat=3))
答案 1 :(得分:2)
您可以使用itertools.product
:
>>> from itertools import product
>>> list(product({0, 1, 2, 3}, repeat=3))
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 2, 0), (0, 2, 1), (0, 2, 2), (0, 2, 3), (0, 3, 0), (0, 3, 1), (0, 3, 2), (0, 3, 3), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 0, 3), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 0), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 0), (1, 3, 1), (1, 3, 2), (1, 3, 3), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 0, 3), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 0), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 0), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 0, 0), (3, 0, 1), (3, 0, 2), (3, 0, 3), (3, 1, 0), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 0), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 3, 0), (3, 3, 1), (3, 3, 2), (3, 3, 3)]
>>>
答案 2 :(得分:2)
您可以使用itertools.product()
功能:
from itertools import product
for i, x, t in product(range(4), repeat=3):
print (i, x, t)
演示:
>>> from itertools import product
>>> for i, x, t in product(range(4), repeat=3):
... print (i, x, t)
...
(0, 0, 0)
(0, 0, 1)
(0, 0, 2)
(0, 0, 3)
(0, 1, 0)
# ... truncated for readability ...
(3, 2, 3)
(3, 3, 0)
(3, 3, 1)
(3, 3, 2)
(3, 3, 3)
答案 3 :(得分:1)
itertools.product()
是一个很好的解决方案,但是如果你想要一个列表而不是元组列表,你可以使用它:
[ [x,y,z] for x,y,z in itertools.product(range(4), repeat=3)]
或等效列表理解:
[ [x,y,z] for x in range(0,4)
for y in range(0,4)
for z in range(0,4)]