Skip to content Skip to sidebar Skip to footer

Python: Search A Sorted List Of Tuples

Useful information: For information on how to sort a list of various data types see: How to sort (list/tuple) of lists/tuples? .. and for information on how to perform a binary sea

Solution 1:

Take advantage of how lexicographic ordering deals with tuples of unequal length:

# bisect_right would also workindex = bisect.bisect_left(x, ('b',))

It may sometimes be convenient to feed a custom sequence type to bisect:

classKeyList(object):
    # bisect doesn't accept a key function, so we build the key into our sequence.def__init__(self, l, key):
        self.l = l
        self.key = key
    def__len__(self):
        returnlen(self.l)
    def__getitem__(self, index):
        return self.key(self.l[index])

import operator
# bisect_right would *not* work for this one.
index = bisect.bisect_left(KeyList(x, operator.itemgetter(0)), 'b')

Solution 2:

Post a Comment for "Python: Search A Sorted List Of Tuples"