Finding the index of an item in a list

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

    index() returns the first index of value!

    | index(...)
    | L.index(value, [start, [stop]]) -> integer -- return first index of value

    def all_indices(value, qlist):
        indices = []
        idx = -1
        while True:
            try:
                idx = qlist.index(value, idx+1)
                indices.append(idx)
            except ValueError:
                break
        return indices
    
    all_indices("foo", ["foo","bar","baz","foo"])
    

提交回复
热议问题