using bisect on list of tuples but compare using first value only

前端 未结 4 1321
旧时难觅i
旧时难觅i 2021-01-18 14:15

I read that question about how to use bisect on a list of tuples, and I used that information to answer that question. It works, but I\'d like a more generic so

4条回答
  •  滥情空心
    2021-01-18 14:47

    bisect supports arbitrary sequences. If you need to use bisect with a key, instead of passing the key to bisect, you can build it into the sequence:

    class KeyList(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):
            return len(self.l)
        def __getitem__(self, index):
            return self.key(self.l[index])
    

    Then you can use bisect with a KeyList, with O(log n) performance and no need to copy the bisect source or write your own binary search:

    bisect.bisect_right(KeyList(test_array, key=lambda x: x[0]), 5)
    

提交回复
热议问题