Python 基于搜索查询的排序列表
我有一个字符串列表,我必须根据一些搜索字符串对其进行排序Python 基于搜索查询的排序列表,python,python-3.x,list,sorting,Python,Python 3.x,List,Sorting,我有一个字符串列表,我必须根据一些搜索字符串对其进行排序 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'] searchquery_startsw
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']
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)]
在排序列表中,第一个元素是搜索字符串删除空格的精确匹配,第二个元素也是空格的精确匹配,第三个元素是Depot的部分匹配(按字母顺序),第四个元素也是Home的部分匹配(按字母顺序放在Depot之后)
到目前为止我做了什么:
Sorted list: ['HomeDepot 1346','Home Depot','Depot Home','Rollins Home Furniture']
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)]
我知道我可以做类似的事情,但我正在寻找更具蟒蛇风格的方法来实现这一点。感谢所有帮助您可以定义一个自定义函数,对给定搜索查询的单词进行排序,然后将其与排序的结合使用
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']
您可以调整每个单独检查的条件和权重,以细化您的结果。此列表失败=['Depot Home'、'Rollins Home Furniture'、'HomeDepot 1346'、'HomeDepot'、'Cryce Depot'、'China Home'、'China Home'、'Rollins Home']我期待:['HomeDepot 1346'、'HomeDepot'、'Depot Home Home Home Home'、'Cryce Home'、'China Home'、'Rollins Home Furniture']你似乎有明确的规则,哪些词在哪些词之前。只需将这些规则编码到函数
search\u for\u home\u depot
中,为要首先列出的单词分配较低的分数。我的回答应该会让你开始找到自己的解决方案。我不是在寻找一种方法,而是一种更快、更简单的方法。它是否也可以在Python中实现,或者我可能需要一些Python全文搜索库。然而,你值得投一票。