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 开发者_如何学Pythonuse bisect for lists of items that aren't made entirely of things with a natural sort order?
You need to add an __lt__
method; this is now what is used for comparisons instead of __cmp__
精彩评论