给定 2 个列表,从两个列表中找到一个随机固定大小的子集,使得每个列表中至少有一个值

假设我有 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']


繁花如伊
浏览 232回答 3
3回答

扬帆大鱼

您可以random.sample()为此使用:import randoml1 = ['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 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'] .... ]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python