Finding the index of an item in a list

后端 未结 30 3249
你的背包
你的背包 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 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.

提交回复
热议问题