如何在python中获得字典中值之间的最小差值

如何在python中获得字典中值之间的最小差值,python,dictionary,difference,Python,Dictionary,Difference,如何在python中获得字典中值之间的最小差异 例如 差值=20 如果有更多的项目,它应该返回它们之间的最小差异 dict = {1: 60, 2: 40, 3: 10} 差值=20 对字典中的页面值列表进行排序(通过dict.values获取),并将此排序列表分配给一个新名称(可能称为排序页面值)。创建一个名为minimum_difference的新变量,将其设置为一个非常高的整数。循环浏览已排序的_页面_金额(跳过第一个),将金额与上一个金额进行比较,如果差异较小,则将最小_差异设置为此值

如何在python中获得字典中值之间的最小差异

例如

差值=20

如果有更多的项目,它应该返回它们之间的最小差异

dict = {1: 60, 2: 40, 3: 10}
差值=20


对字典中的页面值列表进行排序(通过
dict.values
获取),并将此排序列表分配给一个新名称(可能称为排序页面值)。创建一个名为minimum_difference的新变量,将其设置为一个非常高的整数。循环浏览已排序的_页面_金额(跳过第一个),将金额与上一个金额进行比较,如果差异较小,则将最小_差异设置为此值。然后在循环外返回或打印最小差值。

students={1:60,2:40,3:10}
    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 
val=[]#Dict存储Dict学生的值 对于students.items()中的x,y:#将值存储到Val列表 val.append(y) ans=0#用0实例化答案
if(len(val)您的代码在哪里遇到问题?这是一个页面分配问题,学生会获得一定数量的页面。这里的dict长度表示学生人数。这些值是分配给他们的页面。我想找出它们之间的最小差异。虽然此代码可以回答问题,但提供了有关原因和/或方式的其他上下文此代码回答了该问题,提高了其长期价值。以下答案答案中的解释应该是自包含的。答案本身应该包含所需信息。但因此,请不要仅复制其他答案。如果需要,您可以明确参考其他答案。对于给您带来的不便和答案,我们深表歉意没有被复制。我知道它没有被复制。我的意思是,如果你描述代码的作用,你的答案可能会更好。但不要在这样做的时候只是重复另一个答案。
    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