bisect on a list of lists

Peter Otten __peter__ at web.de
Fri Mar 9 23:27:36 CET 2007


Paulo da Silva wrote:

> What is the best way to have something like the bisect_left
> method on a list of lists being the comparision based on an
> specified arbitrary i_th element of each list element?

A simple way that leaves the lists untouched:

>>> import bisect, random
>>> from operator import itemgetter
>>> items = [random.sample(xrange(10), 3) for _ in range(7)]
>>> items.sort(key=itemgetter(2))
>>> items
[[1, 7, 0], [9, 6, 1], [9, 8, 1], [9, 3, 2], [2, 1, 3], [9, 2, 4], [5, 2,
7]]
>>> class C(object):
...     def __init__(self, value, index):
...             self.value = value
...             self.index = index
...     def __cmp__(self, other):
...             return cmp(self.value, other[self.index])
...
>>> bisect.bisect_left(items, C(2, 2))
3

Peter



More information about the Python-list mailing list