问题描述
如何在python中获得字典中值之间的最小差异。
例如
dict = {1: 60,2: 40}
差异 = 20
如果有更多的项目,它应该返回它们之间的最小差异。
dict = {1: 60,2: 40,3: 10}
差异 = 20
解决方法
对字典中的页面值列表进行排序(通过 dict.values
获取)并将这个排序列表分配给一个新名称(可能称为 sorted_page_amounts 之类的名称)。创建一个名为 minimum_difference 的新变量,设置为一个非常大的整数。循环遍历 sorted_page_amounts(跳过第一个),将数量与前一个进行比较,如果差异较小,则将 minimum_difference 设置为此值。然后在循环外返回或打印最小差异。
students = {1: 60,2: 40,3: 10} # Base Dict
val = [] # Dict to store values of dict students
for x,y in students.items(): # Store Values To Val list
val.append(y)
ans = 0 # Instantiate Answer With 0
if(len(val) <= 1):
# If Length is 1 or less that means difference is number it self
ans = val[0]
else:
ans = val[0] # Else Store first element in ans as temp value.
for i in range(1,len(val)): # And Check for all elements except 1
temp = abs(val[i-1] - val[i]) # Store Difference in temp
if(temp < ans): # if the temp is less that previous ans then change value of ans.
ans = temp
return ans # Return the Answer