Finding the index of an item in a list

后端 未结 30 3261
你的背包
你的背包 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:41

    Let’s give the name lst to the list that you have. One can convert the list lst to a numpy array. And, then use numpy.where to get the index of the chosen item in the list. Following is the way in which you will implement it.

    import numpy as np
    
    lst = ["foo", "bar", "baz"]  #lst: : 'list' data type
    print np.where( np.array(lst) == 'bar')[0][0]
    
    >>> 1
    

提交回复
热议问题