python 返回列表索引_python怎么返回列表元素索引?

时间:2025-04-19 14:42:57

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((str2))

输出结果:3

2、循环遍历列表并返回元素索引def get_same_element_index(ob_list, word):

return [i for (i, v) in enumerate(ob_list) if v == 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教程网。