1. 程式人生 > >遍歷列表,找出具體元素的索引

遍歷列表,找出具體元素的索引

問:從列表中找出所有數字2的索引號:

name = ['d', 'a', 'b', 'c', 'd', 2, 'b', 'c', '2', 2, 'b', 'a', 2, 2, 'a', 'hello', 'world', 2, 'peng']

first_position = 0

for i in range(name.count(2)):
    next_position = name[first_position:].index(2)
    print 'the index is: ', next_position + first_position
    first_position += next_position + 1