gpt4 book ai didi

python - Bisect,是否可以使用降序排序列表?

转载 作者:IT老高 更新时间:2023-10-28 20:41:25 26 4
gpt4 key购买 nike

如何在降序排序的列表上使用 bisect 模块?例如

import bisect

x = [1.0,2.0,3.0,4.0] # normal, ascending
bisect.insort(x,2.5) # --> x is [1.0, 2.0, 2.5, 3.0, 4.0] ok, works fine for ascending list

# however
x = [1.0,2.0,3.0,4.0]
x.reverse() # --> x is [4.0, 3.0, 2.0, 1.0] descending list
bisect.insort(x,2.5) # --> x is [4.0, 3.0, 2.0, 1.0, 2.5] 2.5 at end, not what I want really

唯一的方法是 insort (insort_right) 或 insort_left - 这两种方法都不适合我。

最佳答案

可能最简单的事情是从库中借用代码并制作自己的版本

def reverse_insort(a, x, lo=0, hi=None):
"""Insert item x in list a, and keep it reverse-sorted assuming a
is reverse-sorted.

If x is already in a, insert it to the right of the rightmost x.

Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
"""
if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if x > a[mid]: hi = mid
else: lo = mid+1
a.insert(lo, x)

关于python - Bisect,是否可以使用降序排序列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2247394/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com