有一列表,某一元素在列表中出现多次,要求求出该元素在列表中的索引位置。
最简单的方案就是直接对所有元素进行遍历。这里不考虑。
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)