利用operator.itemgetter()和sorted()对字典排序
作者:互联网
operator.itemgetter()函数用于从对象中获取元素,一个简单例子
import operator
import numpy
get = operator.itemgetter(0)
# 相当于x[0].
x = numpy.array([1,2,3,4])
get(x)
>>> 1
# 相当于y[0].
y = numpy.array([[1,2,3,4],[5,6,7,8]])
get(y)
>>> array([1, 2, 3, 4])
对字典排序
import operator
z = {'A':8, 'C':5, 'B':3}
get = operator.itemgetter(0) # 按字典的键排序
zsort = sorted(z.items(), key=get, reverse=False)
print(zsort)
>>> [('A', 8), ('B', 3), ('C', 5)]
get = operator.itemgetter(1) # 按字典的值排序
zsort = sorted(z.items(), key=get, reverse=False)
print(zsort)
>>> [('B', 3), ('C', 5), ('A', 8)]
标签:排序,get,operator,sorted,字典,itemgetter,zsort 来源: https://blog.csdn.net/weixin_43486780/article/details/104835875