python itertools.product 错误地给出结果 [(['x'], ([0, 1],), ([0, 1, 2],)]

python itertools.product giving result wrongly as [(['x'],), ([0, 1],), ([0, 1, 2],)]

我有一个列表

e = [['x'], [0, 1], [0, 1, 2]] 

根据这个列表,我想生成以下输出。

[('x', 0, 0), ('x', 0, 1), ('x', 1, 0), ('x', 1, 1), ('x', 2, 0), ('x', 2,1)]

下面是我使用的代码

import itertools
f=[[0], [2], [3]]
e=[['x']if f[j][0]==0 else range(f[j][0]) for j in range(len(f))]
print(e)
List1_=[]
for i in itertools.product(e):
  List1_.append(i)
print(List1_)

但我得到的输出是

[(['x'],), ([0, 1],), ([0, 1, 2],)]

谢谢, 无

这就是 itertools.product 的用途。但是您需要更改第二项和第三项才能创建预期的产品。

另请注意,您需要使用 * 操作数来解包嵌套列表。因为 product 接受多个可迭代对象并计算它们的乘积。因此,您需要传递子列表而不是整个列表。

>>> e = [['x'], [0, 1, 2], [0, 1]]   
>>> list(product(*e))
[('x', 0, 0), ('x', 0, 1), ('x', 1, 0), ('x', 1, 1), ('x', 2, 0), ('x', 2, 1)]

您没有在您的代码中解包 e

>>> list(product(e))
[(['x'],), ([0, 1],), ([0, 1, 2],)]
>>> 
>>> list(product(*e))
[('x', 0, 0), ('x', 0, 1), ('x', 0, 2), ('x', 1, 0), ('x', 1, 1), ('x', 1, 2)]
>>>

引用自Python Docs

itertools.product(*iterables, repeat=1) Cartesian product of input iterables.

Equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B).

如果顺序对您很重要,只需将您的 e 列表重新排序为 :

>>> e = [['x'], [0, 1, 2], [0, 1]]  

然后你可以得到你期望的输出:

>>> list(product(*e))
[('x', 0, 0), ('x', 0, 1), ('x', 1, 0), ('x', 1, 1), ('x', 2, 0), ('x', 2, 1)]