基于Python中与键匹配的条件对字典中的值求和

2024-09-29 02:14:54 发布

您现在位置:Python中文网/ 问答频道 /正文

给一本字典:

dic = {1: 45, 2: 4, 3: 56, 4: 667, 5: 90}

如果它们对应的键大于或等于阈值(比如3),我想将这些值相加,然后将总和除以一个数字(比如100)

我尝试了以下方法:

threshold = 3
num_to_be_divided = 100
s = sum(v for v in dic.values() if dic.keys() > threshold)
prob = s / num_to_be_divided

Tags: to方法inforthreshold字典阈值数字
2条回答

Sum values in a dictionary based on condition that match keys in Python

dic = {1: 45, 2: 4, 3: 56, 4: 667, 5: 90}
X = 3
_sum = sum(v for k,v in dic.items() if k >X)
print(_sum/100)

试试这个:

print(sum(value for key, value in dic.items() if key >= threshold) / num_to_be_divided)

相关问题 更多 >