📜  Python|查找字典中最近的键

📅  最后修改于: 2022-05-13 01:55:16.079000             🧑  作者: Mango

Python|查找字典中最近的键

Python中字典中的键搜索已经讨论过很多次了。但有时,我们可能会遇到一个问题,即我们需要获取与给定键中最近的一个键。让我们讨论可以执行此任务的某些方式。

方法 #1:使用列表理解 + keys() + lambda
上述函数的组合可用于执行在字典中查找最近键的特定任务。 keys函数可用于访问字典中的键,lambda函数可用于制定逻辑和列表推导以将所有内容应用于整个列表。

# Python3 code to demonstrate working of
# Closest key in dictionary
# Using list comprehension + keys() + lambda
  
# initializing dictionary
test_dict = {13 : 'Hi', 15 : 'Hello',  16 : 'Gfg'}
  
# initializing nearest key
search_key = 15.6
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Using list comprehension + keys() + lambda
# Closest key in dictionary
res = test_dict.get(search_key) or test_dict[
      min(test_dict.keys(), key = lambda key: abs(key-search_key))]
  
# printing result 
print("The value to the closest key : " + str(res))
输出 :
The original dictionary is : {16: 'Gfg', 13: 'Hi', 15: 'Hello'}
The value to the closest key : Gfg

方法 #2:使用bisect_left() + OrderedDict()
这种方法一般采用二分查找法寻找最近的数。虽然速度很快,但它会更改排序并返回 2 个可能的最接近值的候选对象,即当前值和下一个键的值。并且只返回键的位置。

# Python3 code to demonstrate working of
# Closest key in dictionary
# Using bisect_left() + OrderedDict()
import collections
import bisect
  
# initializing dictionary
test_dict = collections.OrderedDict()
test_dict = {13 : 'Hi', 15 : 'Hello',  16 : 'Gfg'}
  
# initializing nearest key
search_key = 15.6
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Using bisect_left() + OrderedDict()
# Closest key in dictionary
res = bisect.bisect_left(list(test_dict.keys()), 15.6)
  
# printing result 
print("The position of closest key : " + str(res))
输出 :
The original dictionary is : {16: 'Gfg', 13: 'Hi', 15: 'Hello'}
The position of closest key : 3