【问题标题】:Sorting list based on Search Query基于搜索查询的排序列表
【发布时间】:2018-07-06 06:10:47
【问题描述】:

我有一个字符串列表,我必须根据一些搜索字符串对其进行排序。

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 的部分匹配(字母顺序)在仓库之后下订单)

到目前为止我做了什么:

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 方式来实现这一点。感谢所有帮助

【问题讨论】:

    标签: python python-3.x list sorting


    【解决方案1】:

    您可以定义一个自定义函数,根据您的搜索查询对您的单词进行排名,然后将其与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']
    

    您可以调整每项检查的条件和权重以细化您的结果。

    【讨论】:

    • 此列表失败 = ['Depot Home','Rollins Home Furniture','HomeDepot 1346','Home Depot','Cryce Depot','China Home']
    • 我期待:['HomeDepot 1346','Home Depot','Depot Home','Cryce Depot','China Home','Rollins Home Furniture']
    • 您似乎有明确的规则,哪些词在哪些词之前。只需将这些规则编码到函数search_for_home_depot 中,为您想首先列出的单词分配较低的分数。我的回答应该能让你开始找到自己的解决方案。
    • 我不是在寻找一种方法,而是一种更快、更简单的方法来解决这个问题。它是否也可以在 Python 中实现,或者我可能不得不使用一些 Python 全文搜索库。但是,您应该得到支持。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多