编程语言
首页 > 编程语言> > python – 在排序列表中插入自定义对象

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

作者:互联网

我实现了一个带有数字属性的对象.我想保留根据该属性排序的那些对象的列表,而不需要在每次插入时运行排序方法.我看了一下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,object,sortedlist
来源: https://codeday.me/bug/20190715/1466813.html