为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

繁花如伊 2022-06-22 18:38:57
假设我有 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']
查看完整描述

3 回答

?
扬帆大鱼

TA贡献1799条经验 获得超9个赞

您可以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']]



查看完整回答
反对 回复 2022-06-22
?
交互式爱情

TA贡献1712条经验 获得超3个赞

您可以生成所有这些:


from itertools import combinations


l1 = ['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。


查看完整回答
反对 回复 2022-06-22
?
拉丁的传说

TA贡献1789条经验 获得超8个赞

您可以组合列表并使用生成器函数:


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']

 ....

 ]


查看完整回答
反对 回复 2022-06-22
  • 3 回答
  • 0 关注
  • 220 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号