python - 通过返回对象方法对对象列表进行排序

标签 python list python-2.7 sorting

我有一个对象列表,它有一个函数,可以对几个成员变量进行一些计算并返回一个值。我想根据这个返回值对列表进行排序。

我找到了如何按成员变量对对象列表进行排序,但我想将它们保密 (_variable_name)。

有没有一种类似于直接按对象成员对列表进行排序的方法来实现这一点?

最佳答案

只需将 key 参数用于 sorted() 函数或 list.sort() 方法:

sorted_list = sorted(list_of_objects, key=function_that_calculates)

function_that_calculateslist_of_objects 中的每个条目调用,其结果通知排序。

如果您的意思是每个对象都有一个方法,您可以使用lambdaoperator.methodcaller() object在每个元素上调用方法:

sorted_list = sorted(list_of_objects, key=lambda obj: obj.method_name())

from operator import methodcaller

sorted_list = sorted(list_of_objects, key=methodcaller('method_name'))

请注意,在 Python 中,没有私有(private)属性这样的东西;您的排序功能仍然可以访问它。前导下划线只是一个约定。因此,可以再次使用 lambda 或使用 operator.attrgetter() object 来完成按特定属性的排序。 :

sorted_list = sorted(list_of_objects, key=lambda obj: obj._variable_name)

from operator import attrgetter

sorted_list = sorted(list_of_objects, key=attrgetter('_variable_name'))

关于python - 通过返回对象方法对对象列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27202942/

相关文章:

python - 简单的Python问题: Why can't I assign a variable to a sorted list (in place)?

c++ - C++中的排序列表

python - 如何在 python 中拆分运算符和操作数

c# - 从列表中返回元组计数

python-2.7 - lxml - 无法替换 child 的 child

c++ - 调试从 C++ 调用的 Cython 代码中的崩溃

python - 按顺序打印二叉树,python

python - 希望在 shell 中使用 ffmpeg 来获取元数据

python - 如何强制 Tornado websockets 在握手时生成错误页面

list - Haskell 在某个位置重复元素