Finding the index of an item in a list

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

    To get all indexes:

    indexes = [i for i,x in enumerate(xs) if x == 'foo']
    
    0 讨论(0)
  • 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]
    >>> 
    
    0 讨论(0)
  • 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"])
    
    0 讨论(0)
  • 2020-11-21 05:46

    For those coming from another language like me, maybe with a simple loop it's easier to understand and use it:

    mylist = ["foo", "bar", "baz", "bar"]
    newlist = enumerate(mylist)
    for index, item in newlist:
      if item == "bar":
        print(index, item)
    

    I am thankful for So what exactly does enumerate do?. That helped me to understand.

    0 讨论(0)
  • 2020-11-21 05:48

    A variant on the answer from FMc and user7177 will give a dict that can return all indices for any entry:

    >>> a = ['foo','bar','baz','bar','any', 'foo', 'much']
    >>> l = dict(zip(set(a), map(lambda y: [i for i,z in enumerate(a) if z is y ], set(a))))
    >>> l['foo']
    [0, 5]
    >>> l ['much']
    [6]
    >>> l
    {'baz': [2], 'foo': [0, 5], 'bar': [1, 3], 'any': [4], 'much': [6]}
    >>> 
    

    You could also use this as a one liner to get all indices for a single entry. There are no guarantees for efficiency, though I did use set(a) to reduce the number of times the lambda is called.

    0 讨论(0)
  • 2020-11-21 05:49

    All indexes with the zip function:

    get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]
    
    print get_indexes(2, [1, 2, 3, 4, 5, 6, 3, 2, 3, 2])
    print get_indexes('f', 'xsfhhttytffsafweef')
    
    0 讨论(0)
提交回复
热议问题