Python2按值合并列表列表 [英] Python2 merge list of lists by value
问题描述
我有4个元素的列表,它看起来像:
I have a list of 4 elements and it looks like:
L = [['grape','green',2, 100], ['grape','purple',3,3], ['apple','red',2, 15], ['apple','greed',3, 10],
['apple','red',4, 4], ['banana','yellow',2, 3]]
我希望有一个函数可以通过第一个元素合并该列表,将第二个和第三个元素连接起来,然后对最后一个元素求和以得到输出,例如:
I would like to have a function to merge that list by the first element, concatenate the second and third element, then sum up the last element to get the output like:
[['grape',['green,purple'],[2,3],103],['banana','yellow',2, 3],['apple',['red','green','red'],[2,3,4],29]
我尝试了以下代码:
[(x,sum(map(itemgetter(3),y))) for x,y in itertools.groupby(L, itemgetter(0))], which can successfully sum up the last element, but
[(x,(map(itemgetter(1),y)),(map(itemgetter(2),y)),sum(map(itemgetter(3),y))) for x,y in itertools.groupby(L, itemgetter(0))]
没有按我预期的那样工作.
did not work as I expected.
有什么办法吗?
推荐答案
使用itertools.groupby()
您需要两个单独的迭代:
Using itertools.groupby()
you need two separate iteration:
In [20]: [[i[0], j, k, sum(z)] for i, j, k, z in [zip(*g) for _, g in groupby(L, itemgetter(0))]]
Out[20]:
[['grape', ('green', 'purple'), (2, 3), 103],
['apple', ('red', 'greed', 'red'), (2, 3, 4), 29],
['banana', ('yellow',), (2,), 3]]
这是使用collections.defaultdict
的另一种方法,但不是这种优化方法:
Here is another way using collections.defaultdict
, but not that optimize :
In [34]: d = defaultdict(list)
In [35]: for i, j, k, z in L:
d[i].append((j, k, z))
....:
In [36]: [[i, j, k, sum(z)] for i, j, k, z in [[i, *zip(*values)] for i, values in d.items()]]
Out[36]:
[['banana', ('yellow',), (2,), 3],
['apple', ('red', 'greed', 'red'), (2, 3, 4), 29],
['grape', ('green', 'purple'), (2, 3), 103]]
请注意,列表中的*zip(...)
称为就地解包,仅在python 3.5+中可用.
Note that *zip(...)
within a list is called in-place unpacking and is only available in python 3.5+.
这篇关于Python2按值合并列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!