简体   繁体   中英

How to find the min positive number within a list

I have a list:

lst = [0, 500.0, 500.0, 240.0]

and I want to find the index of the smallest number that is positive and above 0.

index_of_small = lst.index(min(lst))

I expect index_of_small to be index of 3 instead of index of 0 .

Try this index_of_small = lst.index(min(filter(lambda x : x > 0, lst))) . Filter before finding min.

Using min() function

lst = [0, 500.0, 500.0, 240.0,1.0,-1.0]

print(min(n for n in lst  if n>0))

O/P:

1.0

One way is to find the min element and then find its index, like in another answer. That however makes two passes over the list. It one pass that will be:

min((a,i) for i, a in enumerate(lst) if a>0)[1]

This uses the fact that tuples are compared element by element, left to right.

您需要摆脱0并找到最小值,然后获取此最小值的索引

lst.index(min(i for i in lst if i > 0))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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