我有一个数组列表
test_list =[[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15],
[16,17,18,19,20]]
所以我想在随机选择2列时打印出所有可能的数组,例如,我可以选择第1列和第2列,也可以选择第2列和第4列,或者......
a = [[1,2],
[6,7],
[11,12],
[16,17]]
b =[[2,4],
[7,9],
[12,14],
[17,19]]
我可以使用my_list = [[row[0], row[1]] for row in test_list]
选择2个已分配的列。但我不确定如何随机选择2列并打印出所有可能的输出。
答案 0 :(得分:1)
我们可以使用itertools.combinations
来获取特定大小的所有组合。
from itertools import combinations
def transpose(mat):
return list(zip(*mat))
test_list = [[1, 2, 3, 4, 5],
[6, 7, 8, 9, 0]]
pairs = (transpose(x) for x in combinations(transpose(test_list), 2))
for pair in pairs:
print(pair)
给我们
[(1, 2), (6, 7)]
[(1, 3), (6, 8)]
[(1, 4), (6, 9)]
[(1, 5), (6, 0)]
[(2, 3), (7, 8)]
[(2, 4), (7, 9)]
[(2, 5), (7, 0)]
[(3, 4), (8, 9)]
[(3, 5), (8, 0)]
[(4, 5), (9, 0)]