python - 用python合并复杂矩阵

标签 python list

我有一个复杂的矩阵,如下所示:

[[ ['x', '1', '2', '3', '4'],
   ['y', '5', '6', '7', '8']],

 [ ['x', 'a', 'b', 'c', 'd'],
   ['y', 'e', 'f', 'g', 'h']  ] ]

我想把它变成这样:

['x', '1a', '2b', '3c', '4d'],
['y', '5e', '6f', '7g', '8h']

我绞尽脑汁,却没能得到结果。另外,即使我只有两组嵌套的 5 项长列表,理论上我想解决无限多个相同大小的组的问题。

最佳答案

您可以在此处使用dict:

>>> from operator import add
>>> lis = [[ ['x', '1', '2', '3', '4'],
   ['y', '5', '6', '7', '8']],
 [ ['x', 'a', 'b', 'c', 'd'],
   ['y', 'e', 'f', 'g', 'h']  ] ]
>>> dic = {}
for item in lis:
    for x in item:
        k, v = x[0], x[1:]
        if k in dic:
            dic[k] = map(add, dic[k], v)
        else:
            dic[k] = v
...             
>>> dic
{'y': ['5e', '6f', '7g', '8h'], 'x': ['1a', '2b', '3c', '4d']}
#list of lists
>>> [[k] + v for k, v in dic.iteritems()]
[['y', '5e', '6f', '7g', '8h'], ['x', '1a', '2b', '3c', '4d']]

使用 zipreduce 和列表理解的另一个解决方案:

>>> from operator import add
>>> def func(x, y):
...     return map(add, x, y[1:])

>>> [[item[0][0]] + reduce(func, item[1:], item[0][1:])  for item in zip(*lis)]
[['x', '1a', '2b', '3c', '4d'], ['y', '5e', '6f', '7g', '8h']]

关于python - 用python合并复杂矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18932306/

相关文章:

python - 在 python 中创建字符串数组的最佳方法是什么?

python - 根据异常(exception)列表删除选择性连字符/标点符号

Python 无法正确求和列表

C 将列表从结构传递到另一个函数

Python Django 异步请求处理

python - 谷歌应用引擎: "Cannot create a file when that file already exists"

python - 如何从父小部件禁用所有用户输入小部件(按钮、条目..)?

python - 如何获得数组中不存在的最小正整数

c# - 如何删除列表中的重复对

c# - 从托管 C++ 到 C# 的结构列表