【问题标题】:return key of minimum value [duplicate]返回最小值的键[重复]
【发布时间】:2020-05-24 19:10:15
【问题描述】:

我想在 Python 中返回 dictionary 中最小值的键。键值对的值会有几个数字,即dict[current] = (total, gone, heuristic)。如何返回最小消失值的键?

【问题讨论】:

标签: python dictionary


【解决方案1】:

min 与 lambda 查找函数一起使用:

min(d, key=lambda k: d[k][1])

【讨论】:

  • 我们可以在这里使用itemgetter吗?
【解决方案2】:

简单地说,遍历字典:

d = {1: (1,2,3), 2: (2,4,5), 4: (5,0,2)}
best = None
mn = 99999999 # if you have values more than this, then use float('inf') instead
for k in d:
    if mn > d[k][1]:
        mn = d[k][1]
        best = k 
print(best)
# Output: 4

【讨论】:

    【解决方案3】:

    你可以遍历字典

    best = None
    for key, t in d.items():
        if best is None or t1] < d[best][1]:
            best = key
    return best
    

    【讨论】:

    • 认为应该是tuple[1] &lt; dict[best]
    • @Stuart 是的,你是对的!谢谢
    • dict, tuple 是关键字,请改用dt
    猜你喜欢
    • 2021-11-11
    • 2021-08-10
    • 1970-01-01
    • 2020-06-07
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 2013-07-14
    • 1970-01-01
    相关资源
    最近更新 更多