我有一些要组合的列表,输出应具有list1的第一项,list2的第二项,list3的最后一项。
我尝试了for和append,但不能使用itertools吗?
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8 ,9]
输出应为
[[1,4,7],[2,4,7]...[3,6,9]]
答案 0 :(得分:3)
您也可以尝试考虑简单的{{3}}。是什么让您的问题与众不同,是元素的顺序。这里的关键点是将list1
作为最内层的循环 just 以按您想要的顺序输出。
result = [[i, j, k] for k in list3 for j in list2 for i in list1]
输出
[[1, 4, 7],
[2, 4, 7],
[3, 4, 7],
[1, 5, 7],
[2, 5, 7],
[3, 5, 7],
[1, 6, 7],
[2, 6, 7],
[3, 6, 7],
[1, 4, 8],
[2, 4, 8],
[3, 4, 8],
[1, 5, 8],
[2, 5, 8],
[3, 5, 8],
[1, 6, 8],
[2, 6, 8],
[3, 6, 8],
[1, 4, 9],
[2, 4, 9],
[3, 4, 9],
[1, 5, 9],
[2, 5, 9],
[3, 5, 9],
[1, 6, 9],
[2, 6, 9],
[3, 6, 9]]
答案 1 :(得分:0)
您可以使用numpy
print([list(x) for x in numpy.array(numpy.meshgrid(list1,list2,list3)).T.reshape(-1,len(a))])
输出:
[[1, 4, 7], [1, 5, 7], [1, 6, 7], [2, 4, 7], [2, 5, 7], [2, 6, 7], [3, 4, 7], [3, 5, 7], [3, 6, 7], [1, 4, 8], [1, 5, 8], [1, 6, 8], [2, 4, 8], [2, 5, 8], [2, 6, 8], [3, 4, 8], [3, 5, 8], [3, 6, 8], [1, 4, 9], [1, 5, 9], [1, 6, 9], [2, 4, 9], [2, 5, 9], [2, 6, 9], [3, 4, 9], [3, 5, 9], [3, 6, 9]]