合并多个2D列表,依次考虑轴 [英] Merge multiple 2d lists considering axis in order

查看:90
本文介绍了合并多个2D列表,依次考虑轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目的是按以下顺序组合多个2d列表:

My purpose is to combine multiple 2d list in order such as:

a = [[1,2],[3,1]]
b= [[3,6],[2,9]]
c = [[5,1],[8,10]]
Expected: [[1,2,3,6,5,1],[3,1,2,9,8,10]]

根据该站点的其他建议,我尝试使用类似于以下代码的collections模块:

Following other's advice from this site, I tried to use collections module like the code below:

from collections import Counter
a = [[1,2],[3,1]]
b= [[3,6],[2,9]]
c = [[5,1],[8,10]]
d = [[k,v] for k,v in (Counter(dict(a)) + Counter(dict(b))+ Counter(dict(c))).items()]
print d

但是,结果是[[1, 2], [3, 1], [3, 6], [2, 9]],这不是我期望的.

However, the result is [[1, 2], [3, 1], [3, 6], [2, 9]] which is not what I expected.

您有解决此问题的想法吗?也许是否有功能或模块考虑将轴组合成列表.

Do you have any idea to solve this problem? Maybe if there is function or module to consider the axis to combine the lists.

推荐答案

您可以使用 zip 列表理解:

You can use zip and a list comprehension:

>>> a = [[1,2],[3,1]]
>>> b = [[3,6],[2,9]]
>>> c = [[5,1],[8,10]]
>>> [x+y+z for x,y,z in zip(a, b, c)]
[[1, 2, 3, 6, 5, 1], [3, 1, 2, 9, 8, 10]]
>>>

这篇关于合并多个2D列表,依次考虑轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆