简体   繁体   English

如果key满足条件,则减少python字典值

[英]reduce python dictionary values if key meets condition

I have a python dictionary with string keys, integer values. 我有一个包含字符串键,整数值的python字典。 I want to find the sum of values if the key is not '?'. 如果键不是'?',我想找到值的总和。 I can find the sum using a for loop like this. 我可以像这样使用for循环找到总和。

d = {'a':20, 'b': 20, '?': 10}
sum = 0
for k in d.keys():
    if k != '?':
        sum += d[k]
print "This is my sum: " + sum

For ambition's sake only, I would really like to refactor that into a reduce() function. 仅仅为了野心,我真的想将它重构为reduce()函数。 I took a stab at it: 我捅了一下:

sum = reduce(lambda s, k: s if k == '?' else s += d[k], d.keys())

but I don't really know what I'm doing. 但我真的不知道自己在做什么。 I'm sure someone with better functional chops than I can do this in minutes. 我确信有一个功能更好的人可以在几分钟内做到这一点。 Help me out? 帮帮我?

You can just use the built-in sum() : 你可以使用内置的sum()

>>> d = {'a':20, 'b': 20, '?': 10}
>>> sum(value for key, value in d.items() if key != "?") 
40

Since the key '?' 既然关键'?' can appear only one or zero times, just substract the value for that key from the sum: 只能出现一次或零次,只需从总和中减去该键的值:

>>> sum(d.values()) - d.get('?', 0)
40

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM