在清单列表中添加清单中的项目
问题描述:
如何在清单清单中对清单中的清单对进行配对?在清单列表中添加清单中的项目
A=[[ 1,2 ],[ 3 , 4]]
B=[[ 4,5 ],[ 8 , 9]]
->(1,4),(2,5),(3,8),(4,9)
我已经试过类似zip(*A,*B)
但我越来越SyntaxError: only named arguments may follow *expression
。
到底是什么,我试图做的是将它们添加:
A=[[ 1,2 ],[ 3 , 4]]
B=[[ 4,5 ],[ 8 , 9]]
=[[ 5,7 ],[ 11 , 13]]
(也不起作用):
add= [i+j for i,j in zip(*A,*B)]
答
首先,zip
均为A
和B
然后是zip
个由以前zip
给出这样
result = []
for items in zip(A, B):
for data in zip(*items):
result.append(data)
同样的列表可以简洁地写成一个列表理解,这样
>>> [data for items in zip(A, B) for data in zip(*items)]
[(1, 4), (2, 5), (3, 8), (4, 9)]
答
考虑使用numpy
:
>>> A = [[1, 2], [3, 4]]
>>> B = [[4, 5], [8, 9]]
>>> import numpy
>>> numpy.array(A) + numpy.array(B)
array([[ 5, 7],
[11, 13]])
>>> list(map(list, _))
[[5, 7], [11, 13]]