我有一个字符串列表,我必须根据某些搜索字符串对其进行排序。
My Search String is Home Depot
MyList = ['Depot Home','Rollins Home Furniture','HomeDepot 1346','Home Depot']
预期输出:
Sorted list: ['HomeDepot 1346','Home Depot','Depot Home','Rollins Home Furniture']
在排序列表中,第一个元素是搜索字符串删除空格的精确匹配,第二个也是与空格精确匹配,第三个元素是 Depot 的部分匹配(按字母顺序),第四个元素也是 Home 的部分匹配(按字母顺序排列)订单在 Depot 之后下达)
到目前为止我做了什么:
searchquery_startswith=[w for w in Mylist if w.startswith('HOME DEPOT'.strip())]
searchquery_substring= [w for w in Mylist if ('HOME DEPOT' in w and w not in searchquery_startswith)]
我知道我可以做这样的事情,但我正在寻找更多的Pythonic方法来实现这一点。感谢所有帮助
最佳答案
您可以定义一个自定义函数,根据搜索查询对单词进行排名,然后将其与sorted
结合使用。
def search_for_home_depot(word):
result = 0
if word.lower().startswith('HOME DEPOT'.lower().replace(' ','')):
result += -2
if 'HOME DEPOT'.lower() in word.lower():
result += -1
return result
l = ['Depot Home','Rollins Home Furniture','HomeDepot 1346','Home Depot']
print([search_for_home_depot(x) for x in l])
print(sorted(l, key=search_for_home_depot))
> [0, 0, -2, -1]
> ['HomeDepot 1346', 'Home Depot', 'Depot Home', 'Rollins Home Furniture']
您可以调整每项检查的条件和权重,以细化结果。
关于python - 基于搜索查询的排序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51204017/