[英]Python combinations with list and items in other lists
I try the code below, is there a efficent way to do this? 我尝试下面的代码,有没有一种有效的方法?
c = []
l = [['A1','A2'], ['B1','B2'], ['C1','C2'] ]
for i in range(0, len(l) - 1):
for j in range(i+1, len(l)):
c.append(sorted([l[i][0],l[i][1],l[j][0]]))
c.append(sorted([l[i][0],l[i][1],l[j][1]]))
c.append(sorted([l[i][0],l[j][0],l[j][1]]))
c.append(sorted([l[i][1],l[j][0],l[j][1]]))
print(c)
Out put: 输出:
[['A1', 'A2', 'B1'], ['A1', 'A2', 'B2'], ['A1', 'B1', 'B2'],
['A2', 'B1', 'B2'], ['A1', 'A2', 'C1'], ['A1', 'A2', 'C2'],
['A1', 'C1', 'C2'], ['A2', 'C1', 'C2'], ['B1', 'B2', 'C1'],
['B1', 'B2', 'C2'], ['B1', 'C1', 'C2'], ['B2', 'C1', 'C2']
Try this: 尝试这个:
# group every 2 lists in list l
ll = list(itertools.combinations(l, 2))
# generate all combinations of 3 elements out from each 2 lists
c = [list(itertools.combinations(a + b, 3)) for (a, b) in ll]
# concate all elements
c = sum(c, [])
Or in one line 或一行
from itertools import product
c = [[k] + i for i, j in product(l, l) if j!=i for k in j]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.