2018年7月19日 星期四

[ Python 常見問題 ] Python find first instance of non zero number in list

Source From Here 
Question 
I have a list like this 
  1. myList = [0.0 , 0.00.02.02.0]  
I would like find the location of the first number in list that is not equal to zero. 
  1. myList.index(2.0)  
Works in this example but sometimes the first non zero number will be 1 or 3. Is there a fast way of doing this? 

How-To 
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 # The first index to have value with true value which means not zero

If there is not value as not zero, the None will be returned. 

沒有留言:

張貼留言

[ JS 常見問題 ] Time difference in Nodejs?

Source From   Here   Question   Im trying to figure out a way to   get the time difference in seconds between two dates . For example, diff...