给定字典:
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
根据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)
try this:
print(sum(value for key, value in dic.items() if key >= threshold) / num_to_be_divided)