Finding the index of an item in a list

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

    As indicated by @TerryA, many answers discuss how to find one index.

    more_itertools is a third-party library with tools to locate multiple indices within an iterable.

    Given

    import more_itertools as mit
    
    
    iterable = ["foo", "bar", "baz", "ham", "foo", "bar", "baz"]
    

    Code

    Find indices of multiple observations:

    list(mit.locate(iterable, lambda x: x == "bar"))
    # [1, 5]
    

    Test multiple items:

    list(mit.locate(iterable, lambda x: x in {"bar", "ham"}))
    # [1, 3, 5]
    

    See also more options with more_itertools.locate. Install via > pip install more_itertools.

提交回复
热议问题