Python find first instance of non zero number in list

后端 未结 9 1319
旧巷少年郎
旧巷少年郎 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:08

    Simply use a list comprehension:

    myDict = {x: index for index, x in enumerate(myList) if x}
    

    The indices of the nonzero elements are myDict[element].

    0 讨论(0)
  • 2020-12-30 20:09

    Use filter

    Python 2:

    myList = [0.0, 0.0, 0.0, 2.0, 2.0]
    myList2 = [0.0, 0.0]
    
    myList.index(filter(lambda x: x!=0, myList)[0])       # 3
    myList2.index(filter(lambda x: x!=0, myList2)[0])     # IndexError
    

    Python 3: (Thanks for Matthias's comment):

    myList.index(next(filter(lambda x: x!=0, myList)))    # 3
    myList2.index(next(filter(lambda x: x!=0, myList2)))  # StopIteration
    
    # from Ashwini Chaudhary's answer
    next((i for i, x in enumerate(myList) if x), None)    # 3
    next((i for i, x in enumerate(myList2) if x), None)   # None
    

    You have to handle special case.

    0 讨论(0)
  • 2020-12-30 20:12

    What about using enumerate? Check the enumerate documentation.

    def first_non_zero(mylist):
      for index, number in enumerate(mylist):
        if number != 0: # or 'if number:'
          return index
    
    0 讨论(0)
  • 2020-12-30 20:15

    How'bout this :

    [i for i, x in enumerate(myList) if x][0]
    
    0 讨论(0)
  • 2020-12-30 20:17

    Using next with enumerate is excellent when the array is large. For smaller arrays, I would use argmax from numpy so that you won't need a loop:

    import numpy as np
    
    myList = [0.0, 0.0, 0.0, 2.0, 2.0]
    myArray = np.array(myList)
    np.argmax(myArray > 0)
    3
    
    0 讨论(0)
  • 2020-12-30 20:22

    Use next with enumerate:

    >>> myList = [0.0 , 0.0, 0.0, 2.0, 2.0]
    >>> next((i for i, x in enumerate(myList) if x), None) # x!= 0 for strict match
    3
    
    0 讨论(0)
提交回复
热议问题