0

Let's say I have these two arrays:

u_deteminer = [0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0] u_H = [0.368, 0.303, 0.301, 0.301, 0.301, 0.301, 0.301, 0.301, 0.301, 0.301] 

I am given the value: 1.276819. I would like to find what element in u_determiner is closest to 1.276819 and then grab the u_H element at the same index. Suggestions?

2 Answers 2

2

You can enumerate() over u_deteminer, which will give you the indices and values. Then pass that to min with a key that looks for the smallest difference between the value and number. Then use that index to find the value in the other list:

u_deteminer = [0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0] u_H = [0.368, 0.303, 0.301, 0.301, 0.301, 0.301, 0.301, 0.301, 0.301, 0.301] n = 1.276819 i, val = min(enumerate(u_deteminer), key=lambda t: abs(t[1] - n)) # index and value from u_deteminer with the smallest difference print(i, val) # 5 1.2 # that index in u_H: print(u_H[i]) # 0.301 

If you don't actually need the index, you can just zip the lists together and pass that to min. This will give you the values from both lists where the u_deteminer is closest to your target. Then just use the second:

n = 1.276819 D, H = min(zip(u_deteminer, u_H), key=lambda t: abs(t[0] - n) ) print(H) # 0.301 
Sign up to request clarification or add additional context in comments.

Comments

0

Not sure how you would do this, but I think you can use numpy to find the nearest number in the first array. As for the second array:

u_deteminer = [0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0] u_H = [0.368, 0.303, 0.301, 0.301, 0.301, 0.301, 0.301, 0.301, 0.301, 0.301] a = u_deteminer.index(1.2) b = u_H[a] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.