我正在試圖找到一種方法來查找與dictonary內的字符串最接近的鍵。例如:用字符串在字典中找出最接近的鍵?
data = {'1a': 'This is 1a', '1d': 'This is 1d', '1f': 'This is 1f', '1e': 'This is 1e'}
find_nearest(data, '1b')
#This would return key '1a'
我發現了其他的例子,但大多數處理數字。例如:
data[num] if num in data else data[min(data.keys(), key=lambda k: abs(k-num))]
我能找到一個看起來有前途的一個代碼:
from sortedcontainers import SortedDict
sd = SortedDict((key, value) for key, value in data)
# Bisect for the index of the desired key.
index = sd.bisect(200)
# With that index, lookup the key.
key = sd.iloc[index]
# You can also look ahead or behind to find the nearest key.
behind = sd.iloc[index - 1]
ahead = sd.iloc[index + 1]
所以我想這一點,這裏是我的代碼:
from sortedcontainers import SortedDict
data = {'1a': 'This is 1a', '1d': 'This is 1d', '1f': 'This is 1f', '1e': 'This is 1e'}
sd = SortedDict((key,value) for key,value in data.items())
index = sd.bisect('1b')
key = sd.iloc[index]
print(key)
但是當我運行這段代碼它返回:
1d #Instead of '1a'
我有tr爲了讓代碼能夠工作,每一種方式都是這樣,但我似乎無法做到。有誰知道實現這一目標的快速有效方法?
bisect函數只是做bisect_right,它給你正確的下一個值,而不是最接近的值。 – Schore
需要定義什麼*最接近*在您的要求意味着什麼?...比如,如果有'1a'和'1c',你認爲什麼接近?..以及你會選擇哪一個? –