Finding the index of an item in a list

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

    Another option

    >>> a = ['red', 'blue', 'green', 'red']
    >>> b = 'red'
    >>> offset = 0;
    >>> indices = list()
    >>> for i in range(a.count(b)):
    ...     indices.append(a.index(b,offset))
    ...     offset = indices[-1]+1
    ... 
    >>> indices
    [0, 3]
    >>> 
    

提交回复
热议问题