Python Fastest way to find Indexes of item in list

前端 未结 6 1901
半阙折子戏
半阙折子戏 2020-12-19 06:50

If one was to attempt to find the indexes of an item in a list you could do it a couple different ways here is what I know to be the fastest

aList = [123, \'         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-19 07:17

    To get the index of the item, you can use the dictionary.

    aList = [123, 'xyz', 'zara','xyz', 'abc'];
    #The following apporach works only on lists with unique values
    aList = list(np.unique(aList)); 
    dict = enumerate(aList);
    # get inverse mapping of above dictionary, replace key with values
    inv_dict = dict(zip(dict.values(),dict.keys()))
    # to get index of item by value, use 'inv_dict' and to get value by index, use 'dict'
    valueofItemAtIndex0 = dict[0]; # value = 123
    indexofItemWithValue123 = inv_dict[123]; # index = 0
    

提交回复
热议问题