Finding the index of an item in a list

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

提交回复
热议问题