我有几个列表要连接成一个新的列表列表。例如,列表可能如下所示:
[[], []]
[[3], [1]]
[[], [5]]
[[2,5], []]
并基于此我希望输出看起来像:
[[3, 2, 5], [1,5]]
我们不能假设列表的长度(它们在开头并不总是有两个元素,它们可能有更多)。
这是我尝试过的代码:
list1[l] += list2[l] #where l is an index
答案 0 :(得分:1)
如果我们知道每个顶级列表形状与所有其他列表形状匹配,那么我们可以使用列表推导来做这样的事情:
lists = [
[[], []],
[[3], [1]],
[[], [5]],
[[2,5], []],
]
shape=len(lists[0])
res = [[val for lst in lists for val in lst[i]] for i in range(shape) ]
print(res)
输出:
[[3, 2, 5], [1, 5]]
答案 1 :(得分:1)
lst = [[[], []],[[3], [1]],[[], [5]],[[2,5], []]]
lstFinal = []
for i in range(0,len(lst[0])):
temp = []
for j in range(0,len(lst)):
temp.extend(lst[j][i])
lstFinal.append(temp)
print(lstFinal)
答案 2 :(得分:1)
from functools import reduce
from operator import add
a = [[], []]
b = [[3], [1]]
c = [[], [5]]
d = [[2,5], []]
# transpose
z = zip(a, b, c, d)
# list(z) --> [([], [3], [], [2, 5]), ([], [1], [5], [])]
# flatten
def f(t):
return reduce(add, t)
m = map(f, z)
# result
for thing in m:
print(thing)
>>>
[3, 2, 5]
[1, 5]
>>>