在python中,如何按字典中值的最后一个字母排序?

2024-10-01 17:33:35 发布

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

在下面列出的词典中,如何按名称的最后一个字母进行排序

    list_of_dicts = [
    {'name': 'Jadis', 'year_of_birth': 0, 'gender': 'Female'},
    {'name': 'Peter', 'year_of_birth': 1927, 'gender': 'Male'},
    {'name': 'Susan', 'year_of_birth': 1928, 'gender': 'Female'},
    {'name': 'Edmund', 'year_of_birth': 1930, 'gender': 'Male'},
    {'name': 'Lucy', 'year_of_birth': 1932, 'gender': 'Female'}]

Tags: ofname名称排序字母genderyearmale
2条回答

In case, you want to sort the same list (in place), you can use ".sort" method on the list.

list_of_dicts.sort(key= lambda x: x.get('name')[-1]) # key accepts a function, and we are fetching the last letter of the name. 
print (list_of_dicts)

I hope this helps and counts.

您可以使用内置函数sorted(yourlist=, key=)来完成此操作

其中your_list是您的list_of_dicts,使用key=定义您希望输入列表如何排序的逻辑。在您的情况下,代码是:

sorted_list=sorted(list_of_dicts, key=lambda x: x['name'][-1])

lambda函数允许您为原始列表中的每个xx['name']的最后一个字符进行排序。 当print (sorted_list)出现以下情况时返回:

[{'name': 'Edmund', 'year_of_birth': 1930, 'gender': 'Male'}, {'name': 
'Susan', 'year_of_birth': 1928, 'gender': 'Female'}, {'name': 'Peter', 
'year_of_birth': 1927, 'gender': 'Male'}, {'name': 'Jadis', 'year_of_birth': 
0, 'gender': 'Female'}, {'name': 'Lucy', 'year_of_birth': 1932, 'gender': 
'Female'}]

如您所见,排序后的列表位于“Edmund”->;之后Susan'->;'彼得'->;'Jadis'->;'露西的

相关问题 更多 >

    热门问题