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. 

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...