Reputation: 7529
How can I zip pairs in a list-of-lists?
A=[[ 1,2 ],[ 3 , 4]]
B=[[ 4,5 ],[ 8 , 9]]
->(1,4),(2,5),(3,8),(4,9)
I've tried something like zip(*A,*B)
but I'm getting SyntaxError: only named arguments may follow *expression
.
In the end what I'm trying to do is add them:
A=[[ 1,2 ],[ 3 , 4]]
B=[[ 4,5 ],[ 8 , 9]]
=[[ 5,7 ],[ 11 , 13]]
(also doesn't work):
add= [i+j for i,j in zip(*A,*B)]
Upvotes: 1
Views: 45
Reputation: 369324
Consider using 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]]
Upvotes: 0
Reputation: 239593
First, zip
both A
and B
and then zip
the lists given by the previous zip
, like this
result = []
for items in zip(A, B):
for data in zip(*items):
result.append(data)
The same can be written succinctly as a List Comprehension, like this
>>> [data for items in zip(A, B) for data in zip(*items)]
[(1, 4), (2, 5), (3, 8), (4, 9)]
Upvotes: 2