我有一个复杂的矩阵,如下所示:
[[ ['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']]
使用 zip
、reduce
和列表理解的另一个解决方案:
>>> 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/