欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

用 python 返回列表中指定元素的所有索引。

最编程 2024-06-29 11:48:58
...

python中返回列表中指定元素的所有索引。

1、基本用法

>>> test1
['aa', 'bb', 'aa', 'cc', 'aa', 'cc', 'dd', 'xx', 'bb']
>>> test1.index("aa")
0

 

2、返回所有索引

>>> test1
['aa', 'bb', 'aa', 'cc', 'aa', 'cc', 'dd', 'xx', 'bb']
>>> test1.count("aa")
3
>>> tmp = -1
>>> for i in range(test1.count("aa")):
    tmp = test1.index("aa",tmp + 1,len(test1))
    print("aa",tmp)

    
aa 0
aa 2
aa 4

 

推荐阅读