以关键字列表中的主键和字母顺序作为次关键字的词典排序列表

2024-06-24 13:34:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字典的列表,我希望它们按照关键字列表作为主键排序,或者按字母顺序排列相等的条目。在

目前,我首先按字母顺序排序,然后根据提供的关键字进行排序,由于使用了稳定的排序算法,因此产生了所需的结果。但是,我想我不知道为什么我不能这么做。有人能帮忙吗?在

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

以下是我目前为止的代码:

# 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)

所以实际上我想定义我的“排序过滤器”如下:

^{pr2}$

然后将列表按如下方式排序:

[{ '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'},]    

Tags: keynameprojectid列表by排序关键字
2条回答

您可以使用^{}-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)

输出为:

^{pr2}$

您可以创建一个合适的元组作为排序键。第一部分是您的preferred_projects的索引,默认值是最大索引。第二部分是允许按字母排序的名称:

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

def sort_by(entry):
    name = entry['name']

    try:
        index = preferred_projects.index(name)
    except ValueError:
        index = len(preferred_projects)

    return (index, name)

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'}]    

AllProjects = sorted(AllMyProjectsFromaDatasource, key=sort_by)

for p in AllProjects:
    print p

给出以下输出:

^{pr2}$

相关问题 更多 >