简体   繁体   English

从列表中找到最接近的值?

[英]Finding the closest value from a list?

I have a list of strings:我有一个字符串列表:

list = ["END_BOOTS", "END_CHEST", "MIDAS_SWORD", "SLIME_HAT", "WOOD", "ENDER_PEARL"]

and a keyword:和一个关键字:

keyword = "ENDER_BOOTS"

I need to scan the list to search for a value that is the closest to the keyword.我需要扫描列表以搜索最接近关键字的值。 In this case the closest value would be END_BOOTS.在这种情况下,最接近的值将是 END_BOOTS。 In case when such value can not be found, the code should return false.如果找不到这样的值,代码应该返回 false。

I've tried turning each individual value into a list of characters, sorting it and doing the same to the keyword.我尝试将每个单独的值转换为字符列表,对其进行排序并对关键字执行相同的操作。 After I would compare them and check which list of characters has more common letters with the keyword.在我将它们进行比较并检查哪个字符列表与关键字具有更多常见字母之后。 However that doesn't seem to work very well and it is not very efficient.但是,这似乎效果不佳,效率也不高。

What would be a good solution to this problem in python 3? python 3 中这个问题的一个好的解决方案是什么?

import difflib

a = 'ENDER_BOOTS'
b = 'END_BOOTS'

seq = difflib.SequenceMatcher(None,a,b)
d = seq.ratio()*100
print(d) 

Loop over the list and return the word that gets the highest score遍历列表并返回得分最高的单词

I'd suggest calculating the edit distance between your search keyword and every item in the list, then taking the minimum as your match.我建议计算您的搜索关键字与列表中每个项目之间的编辑距离,然后将最小值作为您的匹配项。

import editdistance

item_list = ["END_BOOTS", "END_CHEST", "MIDAS_SWORD", "SLIME_HAT", "WOOD", "ENDER_PEARL"]

keyword = "SLIMER_HUT"
distances = [editdistance.eval(keyword, item) for item in item_list]
match_index = distances.index(min(distances))

print(distances)
# [10, 9, 10, 2, 10, 9]

print(item_list[match_index])
# SLIME_HAT

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

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