简体   繁体   English

在 Python 中获取最接近 1 的字典键的最快方法

[英]Quickest way to get dictionary key that is closest to 1 in Python

Hi I wanted to ask if this is the quickest and taking the least resources way to get value closest to 1 in dictionary or is there better, more effective way of doing this.嗨,我想问一下,这是在字典中获得最接近 1 的值的最快且占用最少资源的方法,还是有更好、更有效的方法来做到这一点。

import operator

dct = {"a": 0.1, "b": 0.2, "c": 0.7, "d": 1, "e": 0.5}

sorted_orders = sorted(dct.items(), key=operator.itemgetter(1))
sorted_orders = str(sorted_orders.pop()[:1])
a = len(sorted_orders) - 3
sorted_orders = sorted_orders[2:a]
print sorted_orders

Desired output is contents of key closest to 1 here: d所需的输出是此处最接近 1 的键的内容:d

This is how I would do it:这就是我将如何做到的:

closest = sorted(dct.values(), key=lambda x: abs(1-x))[0]

I sort the items with a key that gives the distance between the number and 1 .我使用给出数字和1之间距离的键对项目进行排序。 ( abs(1-x1) ). ( abs(1-x1) )。 The first item, therefore, is the value that is closest to 1 .因此,第一项是最接近1的值。 You could use min() as in the answer by Gábor Erdős, but if you want to know the whole order, use this.您可以在 Gábor Erdős 的回答中使用min() ,但如果您想知道整个顺序,请使用它。

This should do it这应该做

min(list(dct.values()), key=lambda x: abs(x - 1))

Notes:笔记:

  1. This method works for lists as well此方法也适用于列表

  2. This is not the most efficient way.这不是最有效的方式。 A faster approach would be to use bisect更快的方法是使用bisect

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM