Python find first instance of non zero number in list

后端 未结 9 1329
旧巷少年郎
旧巷少年郎 2020-12-30 19:59

I have a list like this

myList = [0.0 , 0.0, 0.0, 2.0, 2.0]

I would like to find the location of the first number in the list that is not e

9条回答
  •  一向
    一向 (楼主)
    2020-12-30 20:30

    Here's a one liner to do it:

    val = next((index for index,value in enumerate(myList) if value != 0), None)
    

    Basically, it uses next() to find the first value, or return None if there isn't one. enumerate() is used to make an iterator that iterates over index,value tuples so that we know the index that we're at.

提交回复
热议问题