![图片[1]-python怎么返回列表元素索引?-uusu优素-乐高,模型,3d打印,编程](http://uusucn.zbbe.cn/wp-content/uploads/2024/01/5ece195a76bde541.jpg)
python中可以使用index()方法返回列表中指定元素的索引。
Python index() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果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)))
输出结果:
原文来自:https://www.py.cn2 在列表 [1, 3, 4, 2, 1, 2, 2] 中的索引: [3, 5, 6]
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END



















































暂无评论内容