我有一份清单如下
[
['a', 1],
['b',2],
['c',1],
['a', 2],
['c', 5]
]
我想以这样的方式规范化这个列表:对于每一个,'a','b','c'等,我在列表中只有一个唯一的条目,对于每个重复的列表,第二个值是是数量被添加,以便我得到类似的东西:
[
['a', 3], # so since 'a' already existed the quantity is added 1 + 2 becomes 3
['b',2],
['c',6] # similarly for 'c' it becomes 1 + 5 = 6
]
如何使用Python做到这一点?
答案 0 :(得分:4)
我建议使用collections.defaultdict()
,如下所示:
from collections import defaultdict
l = [
['a', 1],
['b',2],
['c',1],
['a', 2],
['c', 5]
]
d = defaultdict(int)
for key, value in l:
d[key] += value
print(d.items())
输出:
dict_items([('b', 2), ('a', 3), ('c', 6)])
此外,您可以使用try...expect
代替collections.defaultdict()
...如果您愿意:
d = {}
for key, value in l:
try:
d[key] += value
except KeyError:
d[key] = value
此外,您可以尝试if...else
:
d = {}
for key, value in l:
if key in d:
d[key] += value
else:
d[key] = value
答案 1 :(得分:1)
这是一个很长的路要走,但返回一个列表,而不是一个数据对象
def normalizelist(inp):
out=[]
for key,count in inp:
exist=0
for place, val in enumerate(out):
if (key==val[0]):
out[place][1]+=count
exist=1 #found it, so don't need to make it
break #no need to go further
if (exist==0): #didn't find it, therefor it needs to be added
out.append([key,count])
return out
希望这有帮助!