There is an index method in python. This method returns the index that hits the first search character, but it seems that it cannot return all indexes. Even if I search it, it doesn't come out for some reason (although the search method may be wrong). So I briefly wrote an extended version of the index method that returns multiple indexes that hit the string I searched for.
index_multi.py
def index_Multi(List,liter):
#List is the list body, liter is the character you want to search
index_L = []
for val in range(0,len(List)):
if liter == List[val]:
index_L.append(val)
return index_L
If you give List as the list group you want to search and liter as the character string you want to search, the index that matches the character string you want to search will be returned.
Extract 500 indexes from the elements contained in test_L.
index_test.py
def index_Multi(List,liter):
#List is the list body, liter is the character you want to search
index_L = []
for val in range(0,len(List)):
if liter == List[val]:
index_L.append(val)
return index_L
if __name__ == "__main__":
test_L = [500,0,0,0,0,0,0,500,200]
print index_Multi(test_L,500)
Execution result
[0, 7]
If there is a smart way or method, we will delete this article.
** Addition ** You pointed out. This method can be expressed in one line.
index_test.py
if __name__ == "__main__":
test_L = [500,0,0,0,0,0,0,500,200]
index_num = [n for n, v in enumerate(test_L) if v == 500]
print index_num
Element confirmation in operator, index method, count method
Recommended Posts