【发布时间】:2020-02-07 09:13:10
【问题描述】:
我正在 dict 列表中搜索术语“john”,
我有一个这样的字典列表:
"response": [
{
"name": "Alex T John"
},
{
"name": "Ajo John"
},
{
"name": "John",
}]
我正在使用:
response_query = sorted(response, key = lambda i: i['name'])
response_query 只返回结果的升序,但我需要一个以名字为优先级的结果。
预期结果:
{
"name": "John"
},
{
"name": "Ajo John"
},
{
"name": "Alex T John",
}
应该首先出现包含搜索词的名字。
【问题讨论】:
-
会使用
sorted(response, key = lambda i: i['name'].index('John'))吗? -
你怎么知道名字的哪一部分代表名字?或者你要问的只是
sorted(..., reverse=True)? -
@Shinratensei 但它的显示结果像 John Cap , John Dio , John.But 它应该像 John,John Cap , John Dio
-
sorted(response, key = lambda i: i['name'].index('John') + len(i['name'])),但我觉得你有很多条件,这个 lambda 最终可能无法读取,你应该实现一个更慢但更准确排序的方法
标签: django sorting django-rest-framework