用户定义对象的二等分和列表(python 3)
在 python 3 之前,我使用 bisect 将用户定义的对象插入列表中。 bisect 对此感到满意,因为我的用户定义对象有一个 def __cmp__ 定义了如何比较对象。我已经阅读了 python 3 中不支持 cmp 的基本原理,我对此很满意。我认为对我的旧代码的修复是通过将其转换为元组来“装饰”我的用户定义对象
(integer, user-defined object).
但是,如果我有元组列表,并尝试...
i = bisect_left([list_of_tuples], (integer, user-defined object))
然后我会收到错误“builtins.TypeError” :不可排序的类型...”
那么,(在 python 3 中)如何对不完全由具有自然排序顺序的事物组成的项目列表使用二等分?
Before python 3, I used bisect to insert user-defined objects into a list. bisect was happy with this because my user-defined object had a def __cmp__
that defined how to compare the objects. I've read the rationale for not supporting cmp in python 3 and I'm fine with that. I thought a fix for my old code would be to 'decorate' my user-defined object by turning it into a tuple
(integer, user-defined object).
However, if I have a list of my tuples, and try ...
i = bisect_left([list_of_tuples], (integer, user-defined object))
then I get an error "builtins.TypeError: unorderable types ..."
So, (in python 3) how do I use bisect for lists of items that aren't made entirely of things with a natural sort order?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要添加一个
__lt__
方法;这是现在用于比较的内容,而不是__cmp__
You need to add an
__lt__
method; this is now what is used for comparisons instead of__cmp__