假设在Python中我有3个可变长度的列表:a, b, c
。例如:
a=[1,2,3]
b=[4,5,6]
c=[7,8]
我想得到以上3个列表中两个元素的每一个独特的组合,即
[1,4],[1,5],[1,6],[1,7],[1,8],[2,4],[2,5]...
和3个列表的非唯一组合(例如[1,4,7],[1,4,8],...
)。在
我已经研究过使用itertools
的solution here,这对于两个列表来说是非常好的;但是,当包含第n
个列表时,这个解决方案不再有效,因为唯一组合的长度是n
。在
以下是我尝试过的:
^{pr2}$注意:以上只是一个例子,解决方案应该适用于长度可变的n
列表,并且可能在不同的列表中有相同的值。。。如果你知道我能做什么,我将不胜感激!:)
编辑:正如@SirParselot所要求的,元素必须来自不同的列表
我想您应该做的是使用两个列表的工作解决方案来处理
n
列表。基本上,您可以将输入转换为列表列表,然后执行以下操作:您需要
(a, b, c)
中每对列表的Cartesian product,因此首先需要{a2}来生成列表对,然后{a3}来创建所需的输出元组。在输出
^{pr2}$这是一个处理重复元素的新版本。如果元组中的两个项相等,则不返回元组,并且还通过将
pairs
中的输出输入到一个集合中来消除输出中重复的元组。这是相当有效的,因为pairs
是一个生成器,所以当发现重复项时,就会消除它们。在输出
相关问题 更多 >
编程相关推荐