如何使用key函数的min参数来比较对象的1属性列表?

例子

class SpecialNumber:
    def __init__(self, i):
        self.number = i

li = [SpecialNumber(1), SpecialNumber(3), SpecialNumber(2)]

最佳答案

http://docs.python.org/library/operator.html#operator.attrgetter

from operator import attrgetter
min_num = min(li,key=attrgetter('number'))

互动 session 示例:
>>> li = [SpecialNumber(1), SpecialNumber(3), SpecialNumber(2)]
>>> [i.number for i in li]
[1, 3, 2]
>>> min_num = min(li,key=attrgetter('number'))
>>> print min_num.number
1

关于python - 带有对象列表的Python min函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6085467/

10-11 04:20