在 python 列表理解中枚举三个变量

Enumerating three variables in python list comprehension

我正在尝试打印三个变量列表的所有可能枚举。例如,如果我的输入是:

x = 1
y = 1
z = 1

我希望输出如下:

[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 0], [1, 0, 1], [0, 1, 1], [1, 1, 1]]

如果x,y,z 变量中的任何一个大于1,它将枚举从0 到变量值的所有整数。例如,如果 x=3,则 0、1、2 或 3 可能出现在 3 元素列表的第一个槽中。

现在我正在创建这样的列表理解:

output = [ [x,y,z] for x,y,z in range(x,y,z)]

我觉得范围函数有问题?

您可以使用 itertools 中的 product() 函数,如下所示:

from itertools import product

answer = list(list(x) for x in product([0, 1], repeat=3))
print(answer)

输出

[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]

您可以在列表理解和 itertools.product 函数中使用 range() 函数:

>>> x = 1
>>> y = 1
>>> z = 1
>>> from itertools import product
>>> list(product(*[range(i+1) for i in [x,y,z]]))
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

这种方法也适用于不同的数字:

>>> x = 2
>>> y = 2
>>> z = 2
>>> 
>>> list(product(*[range(i+1) for i in [x,y,z]]))
[(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)]
>>> 

作为使用 product 的解决方案的补充,您还可以使用三元组理解。

>>> x, y, z = 1, 2, 3
>>> [(a, b, c) for a in range(x+1) for b in range(y+1) for c in range(z+1)]
[(0, 0, 0),
 (0, 0, 1),
 (0, 0, 2),
 (some more),
 (1, 2, 2),
 (1, 2, 3)]

+1 是必需的,因为 range 不包括上限。 如果你希望输出是一个列表列表,你可以做 [[a, b, c] for ...].

但是请注意,这显然只适用于您始终拥有三个变量(xyz),而 product 将适用于任意数量的 lists/upper 限制。

如果您需要列表列表的形式(而不是元组列表),您可以在 Kasramvd 的答案输出上使用 map,即:

map(list,list(product(*[range(i+1) for i in [x,y,z]])))