Skip to main content
 首页 » 编程设计

python之使用关键字列表中的主键和字母顺序作为辅助键对字典列表进行排序

2024年10月24日13JeffreyZhao

我有一个字典列表,我希望它们根据关键字列表作为主键进行排序,否则按字母顺序排列相等的条目。

目前,我首先按字母顺序排序,然后根据提供的关键字进行排序,由于使用了稳定的排序算法,这会产生所需的结果。但是,我认为这可以一步完成,但我不知道为什么。谁能帮忙?

其次,我希望能够在关键字排序部分使用关键字而不是完全匹配。我该怎么做?

到目前为止,这是我的代码:

# Define the keywords I want to see first 
preferred_projects = ['project one', 'project two', 'project three'] 
 
# example data 
AllMyProjectsFromaDatasource = [{ 'name': 'project two', 'id': 5, 'otherkey': 'othervalue'}, 
                                { 'name': 'project three', 'id': 1, 'otherkey': 'othervalue'}, 
                                { 'name': 'project one', 'id': 3, 'otherkey': 'othervalue'}, 
                                { 'name': 'abc project', 'id': 6, 'otherkey': 'othervalue'}, 
                                { 'name': 'one project', 'id': 9, 'otherkey': 'othervalue'} 
                               ]     
 
 
def sort_by_preferred(key): 
    """Sort lists out by prefered name.""" 
     sortkey = key['name'] 
     return preferred.index(sortkey) if sortkey in preferred else len(preferred) 
 
# First sort alphabetical     
AllProjects = sorted(AllMyProjectsFromaDatasource, 
                     key=lambda k: k['name']) 
 
# Then sort by keyword 
preferred = preferred_projects 
AllProjects.sort(key=sort_by_preferred) 

所以实际上我想像这样定义我的“排序过滤器”:

preferred_projects = ['one', 'two', 'three'] 

然后像这样对列表进行排序:

[{ 'name': 'one project', 'id': 9, 'otherkey': 'othervalue'} 
 { 'name': 'project one', 'id': 3, 'otherkey': 'othervalue'}, 
 { 'name': 'project two', 'id': 5, 'otherkey': 'othervalue'}, 
 { 'name': 'project three', 'id': 1, 'otherkey': 'othervalue'}, 
 { 'name': 'abc project', 'id': 6, 'otherkey': 'othervalue'},]     

请您参考如下方法:

您可以使用 in-operator找出一个子字符串是否包含在另一个字符串中)。

For the Unicode and string types, x in y is true if and only if x is a substring of y. An equivalent test is y.find(x) != -1. [...] Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True.

您可以使用它来实现关键字排序键。

您将使用其他答案中给出的方法(将元组作为键传递)来实现按字母顺序排序作为辅助键。

这是一个例子:

import pprint 
 
# Define the keywords I want to see first 
preferred_projects = ['one', 'two', 'three'] 
 
# example data 
AllMyProjectsFromaDatasource = [{ 'name': 'project two', 'id': 5, 'otherkey': 'othervalue'}, 
                                { 'name': 'project three', 'id': 1, 'otherkey': 'othervalue'}, 
                                { 'name': 'project one', 'id': 3, 'otherkey': 'othervalue'}, 
                                { 'name': 'abc project', 'id': 6, 'otherkey': 'othervalue'}, 
                                { 'name': 'one project', 'id': 9, 'otherkey': 'othervalue'} 
                               ]     
 
def keyfunc(x): 
    # keyword primary key 
    # (add index to list comprehension when keyword is in name) 
    preferred_key = [float(idx)  
                     for idx, i in enumerate(preferred_projects) 
                     if i in x['name']] 
    # found at least one match in preferred keywords, use first if any, else infinity 
    keyword_sortkey = preferred_key[0] if preferred_key else float('inf') 
    # return tuple to sort according to primary and secondary key 
    return keyword_sortkey, x['name'] 
 
AllMyProjectsFromaDatasource.sort(key=keyfunc) 
 
pprint.pprint(AllMyProjectsFromaDatasource) 

输出是:

[{'id': 9, 'name': 'one project', 'otherkey': 'othervalue'}, 
 {'id': 3, 'name': 'project one', 'otherkey': 'othervalue'}, 
 {'id': 5, 'name': 'project two', 'otherkey': 'othervalue'}, 
 {'id': 1, 'name': 'project three', 'otherkey': 'othervalue'}, 
 {'id': 6, 'name': 'abc project', 'otherkey': 'othervalue'}]