如何获取 orderedDict 中具有最小值的对象?
how get the object which has the minimum value in an 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>]
这些对象中的每一个都具有名称、年龄和来源等属性。我怎样才能得到年龄最小的对象?
试试这个,假设你有 d as orderedDict
import operator
#...
person=sorted(d.values(), key=operator.attrgetter('age'))[0]
print person.age
根据你的需要,你可以使用简单的遍历:
min(orderedDict.values(), key=lambda x: x.age)
但是如果您需要 O(1) 的方式来做到这一点,您需要创建自己的 class,因为 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
我有一个有序的对象字典,
[<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>]
这些对象中的每一个都具有名称、年龄和来源等属性。我怎样才能得到年龄最小的对象?
试试这个,假设你有 d as orderedDict
import operator
#...
person=sorted(d.values(), key=operator.attrgetter('age'))[0]
print person.age
根据你的需要,你可以使用简单的遍历:
min(orderedDict.values(), key=lambda x: x.age)
但是如果您需要 O(1) 的方式来做到这一点,您需要创建自己的 class,因为 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