2024-09-29 02:14:54 发布
网友
给一本字典:
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
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)
试试这个:
相关问题 更多 >
编程相关推荐