微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

例如

dict = {1: 60,2: 40}

差异 = 20

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

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

差异 = 20

解决方法

对字典中的页面值列表进行排序(通过 dict.values 获取)并将这个排序列表分配给一个新名称(可能称为 sorted_pa​​ge_amounts 之类的名称)。创建一个名为 minimum_difference 的新变量,设置为一个非常大的整数。循环遍历 sorted_pa​​ge_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 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。