给定2个列表,从两个列表中找到一个随机的fixedsize子集,这样每个列表中至少有一个值(最好是一致选择的)

2024-09-28 22:14:45 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有两个列表,列表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']


Tags: 方法l1列表单词w1l2w3w2
3条回答

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

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

您可以生成所有这些:

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

l1itertools.combinations生成l1的所有3个长组合,并向其中添加一个l2元素

您可以使用^{}来实现:

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

相关问题 更多 >