I have two lists. List B is like a database to which I need to compare each element of list A, one by one. Lets say
B = [0.6, 1.7, 3, 4.5]
A = [0.6, 0.9, 1.2, 1.5, 2, 2.5, 3, 4, 4.5]
B is a sorted list, so for each A[i] whenever the algorithm finds a number which is >= A[i] in B, it should return that as the output. So my output should look something like:
C = [0.6, 1.7, 1.7, 1.7, 3, 3, 3, 4.5, 4.5]
Could you please suggest me the simplest solution, avoiding nested loops as much as possible?
If you can use a 3rd party library, one solution is NumPy via np.searchsorted
:
import numpy as np
B = np.array([0.6, 1.7, 3, 4.5])
A = [0.6, 0.9, 1.2, 1.5, 2, 2.5, 3, 4, 4.5]
res = B[np.searchsorted(B, A)]
array([ 0.6, 1.7, 1.7, 1.7, 3. , 3. , 3. , 4.5, 4.5])
This will be more efficient than a sequential loop or an algorithm based on bisect
from the standard library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With