2018年6月8日 星期五

[ Python 常見問題 ] How to find all occurrences of an element in a list?

Source From Here 
Question 
index() will just give the first occurrence of an item in a list. Is there a neat trick which returns all indices in a list? 

How-To 
You can use a list comprehension: 
>>> alist = [1, 2, 3, 3, 2, 4, 1, 5, 6, 5, 5, 7] 
>>> indices_of_2 = [i for i, v in enumerate(alist) if v == 2] # Collecting index of value=2 
>>> indices_of_2 
[1, 4]

A functional programming way for reference: 
  1. def foldLeft(alist, identity, fun):  
  2.     rst = identity  
  3.     for e in alist:  
  4.         rst = fun(rst, e)  
  5.     return rst  
  6.   
  7. def indexAll(rst, t, n):  
  8.     def ia(rst, t):  
  9.         if t[1] == n:  
  10.             rst.append(t[0])  
  11.         return rst  
  12.     return ia  
  13.   
  14. foldLeft(list(enumerate(alist)), [], indexAll(2))  # Return index of '2' = [1, 4]  
  15. foldLeft(list(enumerate(alist)), [], indexAll(5))  # Return index of '5' = [7, 9, 10]  


沒有留言:

張貼留言

[Linux 常見問題] How to set a file size limit for a directory?

Source From   Here   Question   I   have a directory on my system which is used for a specific reason by applications and users , but I   d...