交互式爱情
您可以生成所有这些:from itertools import combinationsl1 = ['w1','w2','w3','w4','w5']l2 = ['w6','w7','w8']results = []for parts in ( list(p) + [other] for p in combinations(l1,3) for other in l2): results.append(parts)print(results, sep="\n")输出:[['w1', 'w2', 'w3', 'w6'], ['w1', 'w2', 'w3', 'w7'], ['w1', 'w2', 'w3', 'w8'], ['w1', 'w2', 'w4', 'w6'], ['w1', 'w2', 'w4', 'w7'], ['w1', 'w2', 'w4', 'w8'], ['w1', 'w2', 'w5', 'w6'], ['w1', 'w2', 'w5', 'w7'], ['w1', 'w2', 'w5', 'w8'], ['w1', 'w3', 'w4', 'w6'], ['w1', 'w3', 'w4', 'w7'], ['w1', 'w3', 'w4', 'w8'], ['w1', 'w3', 'w5', 'w6'], ['w1', 'w3', 'w5', 'w7'], ['w1', 'w3', 'w5', 'w8'], ['w1', 'w4', 'w5', 'w6'], ['w1', 'w4', 'w5', 'w7'], ['w1', 'w4', 'w5', 'w8'], ['w2', 'w3', 'w4', 'w6'], ['w2', 'w3', 'w4', 'w7'], ['w2', 'w3', 'w4', 'w8'], ['w2', 'w3', 'w5', 'w6'], ['w2', 'w3', 'w5', 'w7'], ['w2', 'w3', 'w5', 'w8'], ['w2', 'w4', 'w5', 'w6'], ['w2', 'w4', 'w5', 'w7'], ['w2', 'w4', 'w5', 'w8'], ['w3', 'w4', 'w5', 'w6'], ['w3', 'w4', 'w5', 'w7'], ['w3', 'w4', 'w5', 'w8']]- itertools.combinations ofl1生成所有 3-long 组合l1并为其添加一个元素l2。
拉丁的传说
您可以组合列表并使用生成器函数:l1 = ['w1', 'w2', 'w3', 'w4', 'w5']l2 = ['w6', 'w7', 'w8']def combos(d, c = []): if len(c) == 4: yield c else: for i in d: s1, s2 = sum(i in c for i in l1), sum(i in c for i in l2) if not (s1 and s2) and len(c) == 3: if i not in c and ((not s1 and i in l1) or (not s2 and i in l2)): yield from combos(d, c+[i]) elif i not in c: yield from combos(d, c+[i])print(list(combos(l1+l2)))输出:[['w1', 'w2', 'w3', 'w6'], ['w1', 'w2', 'w3', 'w7'], ['w1', 'w2', 'w3', 'w8'], ['w1', 'w2', 'w4', 'w6'], ['w1', 'w2', 'w4', 'w7'], ['w1', 'w2', 'w4', 'w8'] .... ['w6', 'w1', 'w7', 'w3'], ['w6', 'w1', 'w7', 'w4'], ['w6', 'w1', 'w7', 'w5'], ['w6', 'w1', 'w7', 'w8'], ['w6', 'w1', 'w8', 'w2'] .... ]