isr*_*kir 1 python sorting dictionary
说,我定义了这个类:
class A:
def __init__(self, x, y):
self.x = x
self.y = y
Run Code Online (Sandbox Code Playgroud)
假设属性x,y保持整数值,我有一个'A'对象的字典 - 让我们调用'a_dict'.我想根据x和y的代数运算结果对这个字典进行排序.我试过这个:
a_dict_sorted = sorted(a_dict.values(), key=100*int(operator.attrgetter('x')) / (float(operator.attrgetter('x')) + float(operator.attrgetter('y')))
Run Code Online (Sandbox Code Playgroud)
显然operator.attrgetter返回一个可调用对象,而不是该属性的值.所以上面的代码给出了这个错误:
TypeError: int() argument must be a string or a number, not 'operator.attrgetter'
Run Code Online (Sandbox Code Playgroud)
对那样的字典排序有什么问题吗?或者我必须预先处理它以创建代数结果然后进行相应的排序?
你可能更好地使用一些匿名函数aka lambda
a_dict_sorted = sorted(a_dict.values(), key = lambda a: 100*int(a.x/(a.x + a.y)) )
Run Code Online (Sandbox Code Playgroud)