gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:04:26 28 4
gpt4 key购买 nike

我实现了一个带有数字属性的对象。我想保留根据该属性排序的这些对象的列表,而无需在每次插入时运行排序方法。我看了一下 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com