合并第二个元素相同的python子列表,并返回sum和第二个元素

时间:2018-12-28 12:07:01

标签: python

在子列表的第二个元素相同的情况下,如何从子列表返回单个列表。例如

提供了一个列表

a = [
[1442, '17-10-17'],
[5437, '19-11-17'],
[5778, '27-11-17'],
[5901, '27-11-17'],
[5875, '27-11-17'],
[5947, '28-11-17']
    ]

它应该返回

[
[1442, '17-10-17'],
[5437, '19-11-17'],
[a[2][0] + a[3][0] + a[4][0], '27-11-17'],
[5947, '28-11-17']
]

3 个答案:

答案 0 :(得分:2)

使用collections.defaultdict

from collections import defaultdict

d_dict = defaultdict(int)
for k,v in a:
    d_dict[v] += k

[[v,k] for k,v in d_dict.items()]

输出:

[[1442, '17-10-17'],
 [5437, '19-11-17'],
 [17554, '27-11-17'],
 [5947, '28-11-17']]

答案 1 :(得分:1)

我知道您想要一个列表,但是您可以使用字典来做-我个人认为这是一种更好的方法。

原始问题答案

让我们看看您的示例变量:

a = [
[1442, '17-10-17'],
[5437, '19-11-17'],
[5778, '27-11-17'],
[5901, '27-11-17'],
[5875, '27-11-17'],
[5947, '28-11-17']
 ]

然后我们将其运行

dates = {}
for item in zip([item[0] for item in a], [item[1] for item in a]):
    val, date = item
    try:
        dates[date].append(val)
    except KeyError:
        dates[date]  = [val]

这将返回:

{'17-10-17': [1442], '19-11-17': [5437], '27-11-17': [5778, 5901, 5875], '28-11-17': [5947]}

要对这些数组求​​和并保持字典格式:

for key, value in dates.items():
    dates[key] = [sum(value)]

如果您希望将其转换回列表:

for key, value in dates.items():
    dates_list.append([sum(value), key])

现在dates_list = [[1442, '17-10-17'], [5437, '19-11-17'], [17554, '27-11-17'], [5947, '28-11-17']]


更新的问题答案

如果数组如下所示:

a = [
[1442, '17-10-17', 'a'],
[5437, '19-11-17', 'b'],
[5778, '27-11-17', 'c'],
[5901, '27-11-17', 'c'],
[5875, '27-11-17', 'd'],
[5947, '28-11-17', 'd']
 ]

然后我们运行:

a = [[n[0], [n[2], n[1]]] for n in a]

现在是主代码的编辑版本:

dates = {}
for item in zip([item[0] for item in a], [item[1] for item in a]):
    val, date = item
    try:
        dates[tuple(date)].append(val)
    except KeyError:
        dates[tuple(date)]  = [val]

然后将其转换回您最初想要的格式:

dates_list = []
for key, value in dates.items():
    dates_list.append([sum(value), *key])

完整代码为:

a = [
[1442, '17-10-17', 'a'],
[5437, '19-11-17', 'b'],
[5778, '27-11-17', 'c'],
[5901, '27-11-17', 'c'],
[5875, '27-11-17', 'd'],
[5947, '28-11-17', 'd']
 ]

a = [[n[0], [n[2], n[1]]] for n in a]


dates = {}
print(list(zip([item[0] for item in a], [item[1] for item in a])))

for item in zip([item[0] for item in a], [item[1] for item in a]):
    val, date = item
    try:
        dates[tuple(date)].append(val)
    except KeyError:
        dates[tuple(date)]  = [val]
    print('val=',val , 'date=', date)
print(dates)

dates_list = []
for key, value in dates.items():
    dates_list.append([sum(value), *key])
    print('key=',key,'value=',value)
print(dates_list)

答案 2 :(得分:0)

这将执行所需的转换:

from collections import OrderedDict

b = OrderedDict()
for x, y in a:
    b.setdefault(y, 0)  #This will ensure every new key is initialised with zero
    b[y] += x           #This will add the corresponding value to zero or previous sum

a = [[y, x] for x, y in b.items()]

输出将是:

[[1442, '17-10-17'],
 [5437, '19-11-17'],
 [17554, '27-11-17'],
 [5947, '28-11-17']]