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

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-09-27
  • 2021-07-05
  • 2021-11-27
  • 2022-12-23
  • 2022-12-23
  • 2021-11-09
猜你喜欢
  • 2021-12-19
  • 2022-12-23
  • 2021-11-05
  • 2022-12-23
  • 2022-12-23
  • 2022-02-04
  • 2021-12-19
相关资源
相似解决方案