将值分配给 python 中的列表并对值求和

Assign Value to a list in python and sum the values

这是 python 中的一个练习,我不能使用 pandas 只是内置的 python 函数。 我有这个列表:

 ['a', 1],
 ['b', 1],
 ['a', 2],
 ['a', 2],

输出应该如下所示:

 ['a', 5],
 ['b', 1],

这是我目前的代码,但我得到的列表基本相同。

result = []

for x,y in list_data:
    if x not in result: 
        result.append([x, int(y)])
    else:
        result[1] += int(y) 
result

您可以创建一个字典来计算总数,然后将其转换回列表:

data = [['c', 2], ['a', 1], ['b', 1], ['a', 2], ['a', 2], ['c', 3]]

totals = {} # could use collections.defaultdict for this part
for k, v in data:
    totals[k] = totals.get(k, 0) + v
print(totals) # {'c': 5, 'a': 5, 'b': 1}
output = [[k, v] for k, v in totals.items()]
# or, output = list(map(list, totals.items()))
# or, output = list(totals.items()) # if you are fine with a list of tuples
print(output) # [['c', 5], ['a', 5], ['b', 1]]

# if you want the output to be sorted alphabetically
output = sorted(output, key=lambda lst: lst[0])
print(output) # [['a', 5], ['b', 1], ['c', 5]]

一行:

import itertools

[[x[0], sum([value[1] for value in x[1]])] for x in itertools.groupby(sorted(list_data), lambda i: i[0])]

详情:

[[x[0], sum([value[1] for value in x[1]])] for x in itertools.groupby(sorted(list_data), lambda i: i[0])]
                                                                      sorted(list_data)                    # sort the list alphabetically
                                                    itertools.groupby(sorted(list_data), lambda i: i[0])   # group by the "key"
                                                                                                           # result: [('a', <itertools._grouper object at 0x000001D6B806F700>), ('b', <itertools._grouper object at 0x000001D6B806F310>)]
  x[0]                                     for x in                                                        # ['a', 'b']
            [value[1] for value in x[1]]   for x in                                                        # [[1, 2, 2], [1]]
        sum([value[1] for value in x[1]])  for x in                                                        # [5, 1]
  x[0], sum([value[1] for value in x[1]])  for x in                                                        # [['a', 5], ['b', 1]]

字典是完成任务的最佳实践。

data = [['a', 1], ['b', 1], ['a', 2], ['a', 2]]
d = {}
for key, value in data:
    d[key] = value + (d[key] if key in d else 0)
# generate list of tuples and sort
out = sorted(d.items())
print(out)

您似乎在将列表视为字典。为了使您的代码正常工作,您需要找到要添加值的结果索引 (result[1]).

但是如果将结果更改为字典,则可以保留几乎相同的代码:

result = dict() # or result = {}
for x,y in list_data:
    if x not in result: 
        result[x] = int(y)
    else:
        result[x] += y

print(result)

Out[1]: {'a': 5, 'b': 1}

如果你想要一个列表,你可以使用:

result_list = []
for x,y in result.items():
    result_list.append([x,y])
    
print(result_list)
[['a', 5], ['b', 1]]