我用数字属性实现了一个对象。我想保留根据该属性排序的那些对象的列表,而无需在每次插入时都运行sort方法。我看了一下bisect模块,但是我不知道是否也可以将其与对象一起使用。
最好的方法是什么?
最佳答案
如果实现 __lt__
方法,则可以对自定义对象执行此操作,因为this is what bisect will use可以比较您的对象。
>>> class Foo(object):
... def __init__(self, val):
... self.prop = val # The value to compare
... def __lt__(self, other):
... return self.prop < other.prop
... def __repr__(self):
... return 'Foo({})'.format(self.prop)
...
>>> sorted_foos = sorted([Foo(7), Foo(1), Foo(3), Foo(9)])
>>> sorted_foos
[Foo(1), Foo(3), Foo(7), Foo(9)]
>>> bisect.insort_left(sorted_foos, Foo(2))
>>> sorted_foos
[Foo(1), Foo(2), Foo(3), Foo(7), Foo(9)]
关于python - 在排序列表中插入自定义对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26840413/