Finding the index of an item in a list

后端 未结 30 3260
你的背包
你的背包 2020-11-21 05:28

Given a list [\"foo\", \"bar\", \"baz\"] and an item in the list \"bar\", how do I get its index (1) in Python?

30条回答
  •  梦如初夏
    2020-11-21 05:59

    using dictionary , where process the list first and then add the index to it

    from collections import defaultdict
    
    index_dict = defaultdict(list)    
    word_list =  ['foo','bar','baz','bar','any', 'foo', 'much']
    
    for word_index in range(len(word_list)) :
        index_dict[word_list[word_index]].append(word_index)
    
    word_index_to_find = 'foo'       
    print(index_dict[word_index_to_find])
    
    # output :  [0, 5]
    

提交回复
热议问题