Finding the index of an item in a list

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

    Python index() method throws an error if the item was not found. So instead you can make it similar to the indexOf() function of JavaScript which returns -1 if the item was not found:

    try:
        index = array.index('search_keyword')
    except ValueError:
        index = -1
    

提交回复
热议问题