python怎么返回列表元素索引?
发布时间:2026-01-13 17:24:53

index()方法可用于python返回列表中指定元素的索引。
Python index() 检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 检查该方法和范围是否包含在指定范围内 python find()方法相同,但如果str不在 在string中会报告一个异常。
直接使用index()只能返回第一个指定元素的索引:
#!/usr/bin/python list=[1,3,4,2,1,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知识。
下一篇 python如何获取整个页面?
