在排序列表中插入自定义对象

use*_*037 4 python object sortedlist

我实现了一个带有数字属性的对象.我想保留根据该属性排序的那些对象的列表,而不需要在每次插入时运行排序方法.我看了一下bisect模块,但我不知道我是否也可以将它与一个对象一起使用.最好的方法是什么?

Bur*_*lid 11

如果实现该__lt__方法,则可以为自定义对象执行此操作,因为这是bisect将用于比较对象的内容.

>>> 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)]
Run Code Online (Sandbox Code Playgroud)