0

我有一个对象的有序字典,

 [<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>]

这些对象中的每一个都具有名称、年龄和来源等属性。我怎样才能得到它的年龄最小的对象?

4

2 回答 2

1

试试这个,假设你有 d 作为 orderedDict

import operator
#...
person=sorted(d.values(), key=operator.attrgetter('age'))[0]
print person.age
于 2018-09-04T02:57:48.840 回答
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
于 2018-09-04T04:04:24.133 回答