Bisect, is it possible to work with descending sorted lists?

前端 未结 10 743
旧巷少年郎
旧巷少年郎 2020-12-09 15:37

How can I use bisect module on lists that are sorted descending? e.g.

import bisect

x = [1.0,2.0,3.0,4.0] # normal, ascending
bisect.insort(x,2.5)  # -->         


        
10条回答
  •  盖世英雄少女心
    2020-12-09 16:15

    One approach is to negate the keys. For example,

    a = [1,2,3,4]
    a.reverse()
    def comparator(a):
        return -a
    b = [comparator(i) for i in a]
    bisect.insort_right(b,comparator(2.5))
    a = [comparator(c) for c in b]
    

    Result: [4, 3, 2.5, 2, 1]

提交回复
热议问题