我试图在python中获得三个不同列表的所有可能组合
说我有三个名单
A = [2,3,4,7,9]
B = [2,3,5]
C = [1,2]
我想返回所有组合为真的A [i] + B [j] -C [k] == 3
D = [[i,j,k] for i in A for j in B for k in C]
以列表格式给出了所有组合,但是如何从这里继续?
答案 0 :(得分:2)
您可以使用itertools.product
的列表理解来检查每个组合,看它是否符合您的条件。
>>> from itertools import product
>>> [(a,b,c) for a,b,c in product(A,B,C) if a + b - c == 3]
[(2, 2, 1), (2, 3, 2), (3, 2, 2)]
答案 1 :(得分:2)
只需添加if i+j-k == 3
即可。您不希望A[i]
等为每个list
编制索引,而i
,j
和k
已经是元素本身。< / p>
D = [[i,j,k] for i in A for j in B for k in C if i+j-k == 3]
您还应该查看itertools.product
以避免这样嵌套:
import itertools
D = [[i,j,k] for i,j,k in itertools.product(A, B, C) if i+j-k == 3]
答案 2 :(得分:0)
只需在最后添加条件:
>>> D = [[i,j,k] for i in A for j in B for k in C if i + j - k == 3]
>>> D
[[2, 2, 1], [2, 3, 2], [3, 2, 2]]