Using bisect in a tuple list?

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

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

How can I divide this list in half according to [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 insert in bisect

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

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

+6
source share
3 answers

You can highlight the values ​​in separate lists.

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

Please note that for bisect to work, your data really needs to be ordered ...

+2
source

In some cases, just plain

 bisect(list_of_tuples, (3, None)) 

will be sufficient.

Since None will compare less than any integer, this will give you the index of the first tuple starting with at least 3 or len(list_of_tuples) if they are all less than 3. Note that list_of_tuples sorted.

+7
source

Check the bottom of the documentation: http://docs.python.org/3/library/bisect.html . If you want to compare with something other than the element itself, you must create a separate list of so-called keys. In your case, an int list containing only [1] tuples. Use this second list to calculate the index using bisect. Then use this to insert the element into the source (list of tuples) and the key ([1] tuple) into the new list of keys (list of integers).

+1
source

All Articles