Eisen
Eisen

Reputation: 1887

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. 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. 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 get

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

how can I do this?

Upvotes: 0

Views: 95

Answers (1)

Serge
Serge

Reputation: 3765

For python list use bisect for greater efficiency

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

Upvotes: 1

Related Questions