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']]
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。
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']
....
]
添加回答
举报
