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']
....
]
添加回答
舉報
