python中可以使用index()方法返回列表中指定元素的索引。
Pythonindex()方法檢測字符串中是否包含子字符串str,如果指定beg(開始)和end(結束)范圍,則檢查是否包含在指定范圍內,該方法與pythonfind()方法一樣,只不過如果str不在string中會報一個異常。
直接使用index()僅可以返回首個指定元素的索引:
#!/usr/bin/python
list=[1,3,4,2,1,2,2]
str2=2
print(list.index(str2))
輸出結果:
3
2、循環遍歷列表并返回元素索引
defget_same_element_index(ob_list,word):
return[ifor(i,v)inenumerate(ob_list)ifv==word]
if__name__=="__main__":
ob_list=[1,3,4,2,1,2,2]
word=2
print("{0}在列表{1}中的索引:{2}".format(word,ob_list,get_same_element_index(ob_list,word)))
輸出結果:
2在列表[1,3,4,2,1,2,2]中的索引:[3,5,6]
以上內容為大家介紹了python怎么返回列表元素索引?希望對大家有所幫助,如果想要了解更多Python相關知識,請關注IT培訓機構:千鋒教育。