多列表积单个列表vs列表数组,需要帮助理解吗

2024-05-14 03:01:26 发布

您现在位置:Python中文网/ 问答频道 /正文

预先警告:我是Python新手,正在自学,所以这个问题可能只有一个微不足道的解决方案——非常感谢您的帮助(和耐心)

好的,总的来说,我想得到一个可变数量列表的所有可能交集的并集。我不太确定如何解释我遇到的一般案例问题,因此为了解决这个问题,我将使用一个包含3个列表的示例(但是,列表的实际数量会有所不同):

假设我们有:

>>>from itertools import product

>>>l1=[1,2,3]
>>>l2=[1,4,5]
>>>l3=[1,6,7]
>>>
>>>array=[l1,l2,l3]
>>>
>>>
>>>list(product(array))
[([1, 2, 3],), ([1, 4, 5],), ([1, 6, 7],)]
>>>
>>>list(product(l1,l2,l3)
[(1, 1, 1), (1, 1, 6), (1, 1, 7), (1, 4, 1), (1, 4, 6), (1, 4, 7), (1, 5, 1), (1, 5, 6), (1, 5, 7), (2, 1, 1), (2, 1, 6), (2, 1, 7), (2, 4, 1), (2, 4, 6), (2, 4, 7), (2, 5, 1), (2, 5, 6), (2, 5, 7), (3, 1, 1), (3, 1, 6), (3, 1, 7), (3, 4, 1), (3, 4, 6), (3, 4, 7), (3, 5, 1), (3, 5, 6), (3, 5, 7)]

我的问题是:

  1. 为什么不list(product(array)) == list(product(l1,l2,l3))
  2. 使用array,如何获得与list(product(l1,l2,l3))相同的输出

有关更多上下文:

最终,目标是得到列表交叉点的所有可能组合的并集。即:

1>>>for x in product(l1,l2,l3):
...     newArray.append(reduce(set.intersection, [set(e) for e in array])
2>>>u=reduce(set.union, [set(e) for e in newArray])
3>>>u
set([1])

除了,因为我不知道我将有多少个列表(在我的代码中,它们被循环附加到array),我希望1行类似于for x in product(array):,而不是for x in product(l1,l2,l3):


Tags: inl1reduce列表for数量productarray
1条回答
网友
1楼 · 发布于 2024-05-14 03:01:26

1) Why doesn't list(product(array))=list(product(l1,l2,l3))?

嗯,itertools.product()接受iterables,然后在它们之间产生笛卡尔积。所以,当你做list(product(array))的时候,你基本上是在试着取一个list(?)的笛卡尔积,并注意到输出中的逗号表示一个list和空iterable之间的笛卡尔积

2) Using array, how can I get the same output as list(product(l1,l2,l3))?

请注意,您的问题归根结底是在调用函数时将arr列表转换为*args。我们有*运算符,因此要得到答案,只需执行以下操作:

product(*arr)

python documentation

If the syntax *expression appears in the function call, expression must evaluate to an iterable. Elements from this iterable are treated as if they were additional positional arguments; if there are positional arguments x1, ..., xN, and expression evaluates to a sequence y1, ..., yM, this is equivalent to a call with M+N positional arguments x1, ..., xN, y1, ..., yM.

既然你必须提到你在自学, python教程中的Unpacking argument lists一节也介绍了这一点

相关问题 更多 >