我有一个字典的列表,我希望它们按照关键字列表作为主键排序,或者按字母顺序排列相等的条目。在
目前,我首先按字母顺序排序,然后根据提供的关键字进行排序,由于使用了稳定的排序算法,因此产生了所需的结果。但是,我想我不知道为什么我不能这么做。有人能帮忙吗?在
其次,我希望能够使用关键字,而不是关键字排序部分的精确匹配。我该怎么做?在
以下是我目前为止的代码:
# 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'},]
您可以使用^{}-operator 来确定子字符串是否包含在另一个字符串中)。在
您可以使用它来实现关键字排序键。在
您将使用另一个答案中给出的方法(将元组作为键传递)来实现作为次键的字母排序。在
下面是一个例子:
输出为:
^{pr2}$您可以创建一个合适的元组作为排序键。第一部分是您的
preferred_projects
的索引,默认值是最大索引。第二部分是允许按字母排序的名称:给出以下输出:
^{pr2}$相关问题 更多 >
编程相关推荐