gpt4 book ai didi

python - python字典中的求和

转载 作者:行者123 更新时间:2023-11-28 19:47:10 24 4
gpt4 key购买 nike

如何使用for循环在python中创建字典

CPO     1
CL 1
SL 1
EL 1
CPO 1
SL 1
CPO 1

所以预期的结果应该如下{'CPO':3,'CL':1,'SL':2,'EL':1}

我试过这个:

avail = defaultdict(list)
cpo = cl = sl= el = 0
for i in hr_line_id:
if i.leave_code == 'CPO':
cpo = cpo + i.no_of_days
avail['cpo'].append(cpo)
elif i.leave_code == 'CL':
cl = cl + i.no_of_days
avail['cl'].append(cl)
elif i.leave_code == 'SL':
sl = sl + i.no_of_days
avail['sl'].append(sl)
print avail

最佳答案

如@JeanFrancoisFabre 所述,这是 collections.Counter 的完美示例:

from collections import Counter

text = """CPO 1
CL 1
SL 1
EL 1
CPO 1
SL 1
CPO 1"""

count = Counter()

for line in text.split("\n"):
k,v = line.split()
count[k] += int(v)

print(count)
Counter({'CPO': 3, 'SL': 2, 'CL': 1, 'EL': 1})

如果你想要小写键,你可以使用 count[k.lower()] += int(v):

Counter({'cpo': 3, 'sl': 2, 'cl': 1, 'el': 1})

如果数量总是1,你可以简单地写一行:

Counter(line.split()[0] for line in text.split("\n"))
# Counter({'CPO': 3, 'SL': 2, 'CL': 1, 'EL': 1})

关于python - python字典中的求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46849507/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com