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:
A functional programming way for reference:
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:
A functional programming way for reference:
- def foldLeft(alist, identity, fun):
- rst = identity
- for e in alist:
- rst = fun(rst, e)
- return rst
- def indexAll(rst, t, n):
- def ia(rst, t):
- if t[1] == n:
- rst.append(t[0])
- return rst
- return ia
- foldLeft(list(enumerate(alist)), [], indexAll(2)) # Return index of '2' = [1, 4]
- foldLeft(list(enumerate(alist)), [], indexAll(5)) # Return index of '5' = [7, 9, 10]
沒有留言:
張貼留言