Finding the index of an item in a list

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

    This solution is not as powerful as others, but if you're a beginner and only know about forloops it's still possible to find the first index of an item while avoiding the ValueError:

    def find_element(p,t):
        i = 0
        for e in p:
            if e == t:
                return i
            else:
                i +=1
        return -1
    

提交回复
热议问题