📌  相关文章
📜  在Python按值对字典列表进行排序的方法–使用itemgetter

📅  最后修改于: 2021-04-23 07:56:13             🧑  作者: Mango

本部分的上一篇文章使用lambda函数按值对字典进行排序。 Python按值对字典列表进行排序的方法–使用lambda函数本文旨在使用itemgetter执行此功能并显示可见的差异。

可以使用Itemgetter代替lambda函数来实现类似的功能。输出与sorted()和lambda相同,但内部实现不同。它使用字典键并将其转换为元组。它减少了开销,并且更快,更高效。必须导入“ 运算符 ”模块才能正常工作。该代码说明如下

# Python code demonstrate the working of sorted()
# and itemgetter
  
# importing "operator" for implementing itemgetter
from operator import itemgetter
  
# Initializing list of dictionaries
lis = [{ "name" : "Nandini", "age" : 20}, 
{ "name" : "Manjeet", "age" : 20 },
{ "name" : "Nikhil" , "age" : 19 }]
  
# using sorted and itemgetter to print list sorted by age 
print "The list printed sorting by age: "
print sorted(lis, key=itemgetter('age'))
  
print ("\r")
  
# using sorted and itemgetter to print list sorted by both age and name
# notice that "Manjeet" now comes before "Nandini"
print "The list printed sorting by age and name: "
print sorted(lis, key=itemgetter('age', 'name'))
  
print ("\r")
  
# using sorted and itemgetter to print list sorted by age in descending order
print "The list printed sorting by age in descending order: "
print sorted(lis, key=itemgetter('age'),reverse = True)

输出:

The list printed sorting by age: 
[{'age': 19, 'name': 'Nikhil'}, {'age': 20, 'name': 'Nandini'}, {'age': 20, 'name': 'Manjeet'}]

The list printed sorting by age and name: 
[{'age': 19, 'name': 'Nikhil'}, {'age': 20, 'name': 'Manjeet'}, {'age': 20, 'name': 'Nandini'}]

The list printed sorting by age in descending order: 
[{'age': 20, 'name': 'Nandini'}, {'age': 20, 'name': 'Manjeet'}, {'age': 19, 'name': 'Nikhil'}]
    itemgetter比lambda的优势
  • 性能:在时间范围内,itemgetter的性能优于lambda函数。
  • 简洁::与lambda函数相比,访问多个值时,itemgetter看起来更加简洁。
    itemgetter(1,3,4,5)  ---> Looks more concise
    key(s[1], s[2], s[3], s[4]) ---> Looks less concise