Finding the index of an item in a list

后端 未结 30 3327
你的背包
你的背包 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]
    
    0 讨论(0)
  • 2020-11-21 06:01

    Simply you can go with

    a = [['hand', 'head'], ['phone', 'wallet'], ['lost', 'stock']]
    b = ['phone', 'lost']
    
    res = [[x[0] for x in a].index(y) for y in b]
    
    0 讨论(0)
  • 2020-11-21 06:02

    Since Python lists are zero-based, we can use the zip built-in function as follows:

    >>> [i for i,j in zip(range(len(haystack)), haystack) if j == 'needle' ]
    

    where "haystack" is the list in question and "needle" is the item to look for.

    (Note: Here we are iterating using i to get the indexes, but if we need rather to focus on the items we can switch to j.)

    0 讨论(0)
  • 2020-11-21 06:03

    If you want all indexes, then you can use NumPy:

    import numpy as np
    
    array = [1, 2, 1, 3, 4, 5, 1]
    item = 1
    np_array = np.array(array)
    item_index = np.where(np_array==item)
    print item_index
    # Out: (array([0, 2, 6], dtype=int64),)
    

    It is clear, readable solution.

    0 讨论(0)
  • 2020-11-21 06:03

    There is a chance that that value may not be present so to avoid this ValueError, we can check if that actually exists in the list .

    list =  ["foo", "bar", "baz"]
    
    item_to_find = "foo"
    
    if item_to_find in list:
          index = list.index(item_to_find)
          print("Index of the item is " + str(index))
    else:
        print("That word does not exist") 
    
    0 讨论(0)
  • 2020-11-21 06:04

    Finding index of item x in list L:

    idx = L.index(x) if (x in L) else -1
    
    0 讨论(0)
提交回复
热议问题