如何获得orderedDict中具有最小值的对象?

时间:2018-09-04 02:09:54

标签: python object attributes ordereddict

我有一个orderedDict对象,

 [<f.Packet object at 0x07AD7090>, <f.Packet object at 0x07ACA8F0>, <f.Packet object at 0x07ACAC90>, <f.Packet object at 0x07A5F5D0>, <f.Packet object at 0x07ACA410>, <f.Packet object at 0x07ABBF50>, <f.Packet object at 0x07ACA830>]

每个对象都具有名称,年龄和来源等属性。如何获得年龄最小的物体?

2 个答案:

答案 0 :(得分:1)

尝试一次,假设您已将d作为orderedDict

import operator
#...
person=sorted(d.values(), key=operator.attrgetter('age'))[0]
print person.age

答案 1 :(得分:1)

根据需要,可以使用简单的遍历:

min(orderedDict.values(), key=lambda x: x.age)

但是,如果您需要O(1)方法,则需要创建自己的类,因为OrderedDict仅根据插入顺序对项目进行排序。例如,您可以使用Sorted Containers中的SortedDict(或编写您自己的)并进行类似的操作(假设您仍然希望能够根据插入顺序获取商品):

from collections import OrderedDict
from sortedcontainers import SortedDict

class MyOrderedDict(OrderedDict):
     def __init__(self):
             super(MyOrderedDict, self).__init__(self)
             self.sorted = SortedDict()
     def __setitem__(self, key, value):
             super(MyOrderedDict, self).__setitem__(key, value)
             self.sorted[value.age] = value
     def __delitem__(self, key):
             age = super(MyOrderedDict, self).__getitem__(key).age
             super(MyOrderedDict, self).__delitem__(key)
             self.sorted.__delitem__(age)
     def ageIterator(self):
         for age in self.sorted:
             yield (age, self.sorted[age])

orderedDict = MyOrderedDict()
#...

for item in orderedDict:
    # Items in the order of insertions

for age, item in orderedDict.ageIterator():
    # Items by age