Finding the index of an item in a list

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

    All of the proposed functions here reproduce inherent language behavior but obscure what's going on.

    [i for i in range(len(mylist)) if mylist[i]==myterm]  # get the indices
    
    [each for each in mylist if each==myterm]             # get the items
    
    mylist.index(myterm) if myterm in mylist else None    # get the first index and fail quietly
    

    Why write a function with exception handling if the language provides the methods to do what you want itself?

提交回复
热议问题