- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在尝试找到一种方法来找到字典中最接近字符串的键。示例:
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'
我已经尝试了各种方法来让代码正常工作,但我似乎无法做到正确。有谁知道实现此目标的快速有效方法?
最佳答案
平分时,如果找不到精确的索引匹配,算法有 2 个选择。它可以返回左边对象的索引,也可以返回右边对象的索引。看起来 bisect
是 bisect_right
的别名。你可以使用 bisect_left
相反……
当然,这不一定更接近(您还没有真正定义更接近的意思)。事实上,即使像 difflib.SequenceMatcher.ratio()
这样的东西也可能对示例没有帮助,因为它只是查看匹配元素与非匹配元素的比率。
你可以尝试这样的事情:
def find_closest(sd, expected):
index = sd.bisect(expected)
closest_lower = sd.iloc[index]
try:
closest_upper = sd.iloc[index]
except IndexError:
return closest_lower
# assumption -- Your keys are hex values.
# this assumption could be completely wrong, but demonstrates
# how to think of defining a measure of "closeness"
var expected_as_int = int(expected, 16)
def distance(val):
return int(val, 16) - expected_as_int
return min([closest_lower, closest_upper], key=distance)
关于python - 用字符串在字典中找到最近的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36338535/
例如,我有一个父类Author: class Author { String name static hasMany = [ fiction: Book,
代码如下: dojo.query(subNav.navClass).forEach(function(node, index, arr){ if(dojo.style(node, 'd
我有一个带有 Id 和姓名的学生表和一个带有 Id 和 friend Id 的 Friends 表。我想加入这两个表并找到学生的 friend 。 例如,Ashley 的 friend 是 Saman
我通过互联网浏览,但仍未找到问题的答案。应该很容易: class Parent { String name Child child } 当我有一个 child 对象时,如何获得它的 paren
我正在尝试创建一个以 Firebase 作为我的后端的社交应用。现在我正面临如何(在哪里?)找到 friend 功能的问题。 我有每个用户的邮件地址。 我可以访问用户的电话也预订。 在传统的后端中,我
我主要想澄清以下几点: 1。有人告诉我,在 iOS 5 及以下版本中,如果您使用 Game Center 设置多人游戏,则“查找 Facebook 好友”(如与好友争夺战)的功能不是内置的,因此您需要
关于redis docker镜像ENTRYPOINT脚本 docker-entrypoint.sh : #!/bin/sh set -e # first arg is `-f` or `--some-
我是一名优秀的程序员,十分优秀!