Search code examples
pythonpython-3.3

Using bisect in a list of tuples?


I'm trying to figure out how to use bisect in a list of tuples for example

[(3, 1), (2, 2), (5, 6)]

How can I bisect this list according to the [1] in each tuple?

list_dict [(69, 8), (70, 8), ((65, 67), 6)]
tup1,tup2 (69, 8) (70, 8)
list_dict [((65, 67), 6)]
fst, snd ((65, 67),) (6,)

And I'm inserting to bisect

idx = bisect.bisect(fst, tup1[1]+tup2[1])

Which gives me unorderable types: int() < tuple()


Solution

  • You can separate out the values into separate lists.

    from bisect import bisect
    
    data = [(3, 1), (2, 2), (5, 6)]
    fst, snd = zip(*data)
    idx = bisect(fst, 2)
    

    Note however, that for bisect to work, your data really should be ordered...