python - 基于搜索查询的排序列表

标签 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']

在排序列表中,第一个元素是搜索字符串删除空格的精确匹配,第二个也是与空格精确匹配,第三个元素是 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/

相关文章:

java - 用于文本处理(文本挖掘、信息检索、自然语言处理)的 Python 或 Java

python - RecycleView 内的 Kivy 尺寸标签

python - 软件包的 pip 安装可以从源代码安装,但从软件包安装失败

r - 展平具有复杂嵌套结构的列表

Python - 展平字典列表

python - 关于Django RadioSelect初始值

Python多处理退出错误

python - 查找数据框中每列的最高 n 值

python - 将列表中所有元素相加但不包括第一个偶数的函数

python - 如何在现有列表后添加列表但不扩展它?