假设我有2个列表,列表1和列表2这样(例如)
l1 = ['w1', 'w2', 'w3', 'w4', 'w5']
l2 = ['w6', 'w7', 'w8']
是否有一种简短而又甜蜜的方法来获取一个新列表(具有给定的固定大小,例如4),该列表包含两个列表中的单词,从而每个列表中至少有一个单词? (无重复)
4号可能的结果
['w6', 'w2', 'w4', 'w8']
['w2', 'w8', 'w7', 'w4']
['w1', 'w2', 'w6', 'w4']
['w2', 'w3', 'w1', 'w7']
您可以使用random.sample()
:
random.sample()
可能的结果:
import random
l1 = ['w1','w2','w3','w4','w5']
l2 = ['w6','w7','w8']
result = [random.sample(l1,2) + random.sample(l2,2) for i in range(4)]
print(result)
您可以生成所有这些文件:
[['w5', 'w1', 'w8', 'w7'], ['w3', 'w4', 'w7', 'w6'], ['w3', 'w5', 'w6', 'w8'], ['w5', 'w2', 'w7', 'w6']]
输出:
from itertools import combinations
l1 = ['w1','w2','w3','w4','w5']
l2 = ['w6','w7','w8']
results = []
for parts in set( frozenset(list(p) + [other]) for p in combinations(l1,3) for other in l2):
results.append(list(parts))
results.sort()
print(results, sep="\n")