Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify the non-zero element in a list which is close to given number in Python

Tags:

python

I have list like this:

lst = [1, 5, 0, 0, 4, 0]

EDIT: I would like find the location of the first number in list that is not equal to zero and it is closest given number.

a = 3  # (given number)

It should return 4 as index and value too. I tried with this:

min(enumerate(lst), key=lambda x: abs(x[1]-a))

but its shows the 0 element too.

which is the better way for doing this?

like image 931
SubodhD Avatar asked Dec 08 '25 14:12

SubodhD


1 Answers

If I understood you correctly, just filter out the zeros after enumerating:

In [1]: lst = [1, 5, 0, 0, 4, 0]

In [2]: a = 3

In [3]: min(filter(lambda x: x[1] != 0, enumerate(lst)),
            key=lambda x: abs(x[1] - a))
Out[3]: (4, 4)

Your own example does return (4, 4) too for the given values though. With a = 0 there's a difference.

like image 181
Ilja Everilä Avatar answered Dec 10 '25 05:12

Ilja Everilä



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!