安迪_963

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

有一列表,某一元素在列表中出现多次,要求求出该元素在列表中的索引位置。

最简单的方案就是直接对所有元素进行遍历。这里不考虑。

 1 # coding:utf-8
 2 name = list('12345242523552623623')
 3 
 4 first_pos = 0
 5 for i in range(name.count('2')):
 6     pos = name.index('2')
 7     position = first_pos + pos
 8     print('第%d 个索引是: %d' % (i, position))
 9     name = name[pos+1:]
10     first_pos += (pos+1)
方案1:

事实上这里结果没有问题,但有一个潜在隐患,就是在循环过程中对列表进行了修改,所以最好的做好是:将for i in range(name.count('2')):里的name替换成name[:],即拷贝一份。

 1 # coding:utf-8
 2 name = list('12345242523552623623')
 3 
 4 pos = 0
 5 for i in range(name.count('2')):
 6     if pos == 0:
 7         pos = name.index('2')
 8     else:
 9         pos = name.index('2', pos+1)
10     print('第%d个2索引:%d' % (i, pos))
方案2:

方案二利用了内置方法index的可选 参数start。效果相同。

posted on 2016-03-24 15:52  Andy_963  阅读(684)  评论(0编辑  收藏  举报