我有 4 列表,每个列表都包含 3 子列表
L1 = [[sub11],[sub12],[sub13]]
L2 = [[sub21],[sub22],[sub23]]
L3 = [[sub31],[sub32],[sub33]]
L4 = [[sub41],[sub42],[sub43]]
我想从每个列表中随机选择子列表以创建最终的 3 列表
例如,最终的 3 列表可能看起来像
final1 = [[sub13],[sub21],[sub33],[sub42]]
final2 = [[sub12],[sub23],[sub31],[sub43]]
final3 = [[sub11],[sub22],[sub32],[sub41]]
感谢您的帮助
答案 0 :(得分:0)
>>> L1 = [12, 13, 11]
>>> L2 = [22, 23, 21]
>>> L3 = [31, 32, 33]
>>> L4 = [41, 42, 43]
>>> from random import shuffle
>>> L = [L1, L2, L3, L4]
>>> for item in L:
... shuffle(item)
...
>>> F = zip(*L)
>>> final1, final2, final3 = F
>>> final1
(12, 22, 31, 41)
>>> final2
(13, 23, 32, 42)
>>> final3
(11, 21, 33, 43)
答案 1 :(得分:0)
您可以使用random.sample()
然后zip()
结果随机化每个结果:
>>> import random
>>> L1 = [['sub11'],['sub12'],['sub13']]
>>> L2 = [['sub21'],['sub22'],['sub23']]
>>> L3 = [['sub31'],['sub32'],['sub33']]
>>> L4 = [['sub41'],['sub42'],['sub43']]
>>> all_lists = [L1, L2, L3, L4]
>>> random_lists = map(list, list(zip(*(random.sample(item, len(item)) for item in all_lists))))
>>> for i in random_lists:
... print(i)
...
[['sub13'], ['sub22'], ['sub33'], ['sub43']]
[['sub11'], ['sub23'], ['sub32'], ['sub42']]
[['sub12'], ['sub21'], ['sub31'], ['sub41']]
答案 2 :(得分:0)
import random
L1 = [['sub11'],['sub12'],['sub13']]
L2 = [['sub21'],['sub22'],['sub23']]
L3 = [['sub31'],['sub32'],['sub33']]
L4 = [['sub41'],['sub42'],['sub43']]
final = []
for L in [L1, L2, L3, L4]:
final.append(random.sample(L, 1)[0])
print final
输出:
[['sub11'], ['sub22'], ['sub31'], ['sub42']]
根据需要重复多次,以构建更多随机列表。