简体   繁体   English

替换有序列表 python

[英]Replacing in place for ordered list python

feature_min = 0
feature_max = 100
feature_range = np.linspace(feature_min, feature_max, num = 10)
rng = np.random.uniform(0, 100)

I have the above code and I generate a random number between 0-100.我有上面的代码,我生成了一个 0-100 之间的随机数。 Whatever the random number is I want to put it within the sorted feature_range list by replacing it an element in the list depending on where it needs to be.无论随机数是什么,我都想将其放入已排序的feature_range列表中,方法是根据需要将其替换为列表中的一个元素。 The max and the min should never be replaced.永远不要替换最大值和最小值。

For example if my list is例如,如果我的清单是

[0,20,30,40,50,60,70,80,90,100]

and rng = 14 I would replace 20 with 14 to getrng = 14我会用 14 替换 20 以获得

[0,14,30,40,50,60,70,80,90,100]

how can I do this?我怎样才能做到这一点?

For python list use bisect for greater efficiency对于 python 列表,使用 bisect 来提高效率

import bisect
a = [0, 20, 30, 40, 50, 60, 70, 80, 90, 100]
x = 14
i = bisect.bisect(a, x, lo=1, hi=len(a) - 1)
if 0 < i < len(a) - 1:
    a[i] = x
print(i, a)

With numpy use searchsorted , which is numpy's reimplementation of bisect https://numpy.org/doc/stable/reference/generated/numpy.searchsorted.html使用 numpy 使用searchsorted ,这是 numpy 对 bisect https 的重新实现:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM