嵌套列表根据第一个值组合值 [英] nested lists combine values according to first value

查看:95
本文介绍了嵌套列表根据第一个值组合值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

list = [ ['a',14,2], ['b',10,1], ['a',3,12], ['r',5,5], ['r',6,13] ]
result = data_sum(list)

def data_sum(list):
  for set in list:
    current_index = list.index(set)
    string  = set[0]
    for item in list:
      second_index = list.index(each)
      if string == item[0] and current_index != second_index:
        set[0] = item[0]
        set[1] += item[1]
        set[2] += item[2]
        del each

  return list

我的结果应该是

[ ['a',17,14], ['b',10,1], ['r',11,18] ]

如果嵌套列表相同,则根据第一个字符串聚合嵌套列表.

where nested lists are aggregated according to the first string if it's identical.

我认为我不能在这里使用set[],因为它不会根据嵌套列表本身中的元素进行汇总.

I don't think I can use set[] here because it will not sum up according to the elements inside the nested list itself.

  1. 我不确定我是否正确使用了list.index
  2. 到目前为止,输出结果与原始列表完全相同

推荐答案

首先,listsetstring已经是内置函数,因此不建议使用这些名称.我还认为您使问题稍微复杂化了一点,因为您需要做的只是将字母分组在一起,然后对这些值进行一些求和.

Firstly, list, set and string are already builtin functions, so using these names is not recommended. I also think your over complicating the problem slightly, since all you need to do is group the letters together, and do some summing of the values afterwards.

为了使您自己更轻松地解决此问题,您需要以某种方式对每个列表的第一个值进行分组,然后取其后的值之和.一种可能的方法是使用 collections.defaultdict ,然后将相应的值相加:

In order to make this problem easier for yourself, you need to somehow group the first values of each list, and take the sum of the values after that. One possible way is to group the first values with a collections.defaultdict, then sum the corresponding values afterwards:

from collections import defaultdict

lsts = [['a',14,2], ['b',10,1], ['a',3,12], ['r',5,5], ['r',6,13]]

groups = defaultdict(list)
for letter, first, second in lsts:
    groups[letter].append([first, second])
# defaultdict(<class 'list'>, {'a': [[14, 2], [3, 12]], 'b': [[10, 1]], 'r': [[5, 5], [6, 13]]})

result = []
for key, value in groups.items():
    sums = [sum(x) for x in zip(*value)]
    result.append([key] + sums)

print(result)

哪些输出:

[['a', 17, 14], ['b', 10, 1], ['r', 11, 18]]

结果列表也可以用以下列表理解来编写:

The resultant list can also be written with this list comprehension:

result = [[[key] + [sum(x) for x in zip(*value)]] for key, value in groups.items()]

另一种方法是使用 itertools.groupby :

Another way is to use itertools.groupby:

from itertools import groupby
from operator import itemgetter

grouped = [list(g) for _, g in groupby(sorted(lsts), key = itemgetter(0))]
# [[['a', 3, 12], ['a', 14, 2]], [['b', 10, 1]], [['r', 5, 5], ['r', 6, 13]]]

result = []
for group in grouped:
    numbers = [x[1:] for x in group]
    sums = [sum(x) for x in zip(*numbers)]
    result.append([[group[0][0]] + sums])
print(result)

还会输出:

[['a', 17, 14], ['b', 10, 1], ['r', 11, 18]]

注意:第二种方法也可以写成大列表理解:

Note: The second approach could also be written as a big list comprehension:

result = [[[group[0][0]] + [sum(x) for x in zip(*[x[1:] for x in group])]] for group in [list(g) for _, g in groupby(sorted(lsts), key = itemgetter(0))]]

但这是丑陋且不可读的,因此不应使用.

But this is ugly and unreadable, and shouldn't be used.

这篇关于嵌套列表根据第一个值组合值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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