The somewhat arbitrary order of your list is due to the fact that objects are ordered by id (which is derived from the RAM address of the object in CPython) unless they provide some other way to define an ordering.
The easy way to solve your problem is to simply use the built-in list.sort
method (or the sorted
function), passing key=len
as the key function argument.
However, if you want to use bisect
to maintain a sorted list, you can do that too, but your class needs to define the Rich Comparison methods.
You could add these methods to your graph class, but it may be easier (and cleaner) to define a new class as a wrapper.
Here's a simple example that wraps the built-in list
type. It defines a private method, _cmp
to perform length-based comparisons, and the Rich Comparison "magic" methods call _cmp
. For greater efficiency, the Rich Comparison methods should be defined directly, to avoid calling another method, but using _cmp
is easier to read (and to write :) ).
import bisect
class MyList(object):
def __init__(self, data):
self.data = data
def __repr__(self):
return 'MyList({0!r})'.format(self.data)
def _cmp(self, other):
return len(self.data) - len(other.data)
#Rich comparison methods
def __lt__(self, other):
return self._cmp(other) < 0
def __le__(self, other):
return self._cmp(other) <= 0
def __eq__(self, other):
return self._cmp(other) == 0
def __ne__(self, other):
return self._cmp(other) != 0
def __ge__(self, other):
return self._cmp(other) >= 0
def __gt__(self, other):
return self._cmp(other) > 0
data = (
[50, 60],
[10, 20, 30],
[1, 2, 3, 4, 5],
[5, 6],
[7, 8, 9, 10],
)
blist = []
for seq in data:
a = MyList(seq)
bisect.insort(blist, a)
print(a)
print(blist)
print()
output
MyList([50, 60])
[MyList([50, 60])]
MyList([10, 20, 30])
[MyList([50, 60]), MyList([10, 20, 30])]
MyList([1, 2, 3, 4, 5])
[MyList([50, 60]), MyList([10, 20, 30]), MyList([1, 2, 3, 4, 5])]
MyList([5, 6])
[MyList([50, 60]), MyList([5, 6]), MyList([10, 20, 30]), MyList([1, 2, 3, 4, 5])]
MyList([7, 8, 9, 10])
[MyList([50, 60]), MyList([5, 6]), MyList([10, 20, 30]), MyList([7, 8, 9, 10]), MyList([1, 2, 3, 4, 5])]
You may like to take a look at heapq
: you may find it better for your purposes than bisect
. heapq
will (of course) use the Rich Comparison methods if they are defined.