简体   繁体   English

从列表列表中的对中添加项目

[英]Adding items from pairs in list of lists

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 . 我已经尝试过zip(*A,*B)类的东西zip(*A,*B)但是却遇到了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)]

First, zip both A and B and then zip the lists given by the previous zip , like this 首先,同时zip AB ,然后zip先前zip给出的列表,像这样

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 可以像List Complehension这样简洁地编写相同的内容

>>> [data for items in zip(A, B) for data in zip(*items)]
[(1, 4), (2, 5), (3, 8), (4, 9)]

Consider using numpy : 考虑使用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]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM