Finding the index of an item in a list

后端 未结 30 3390
你的背包
你的背包 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 06:02

    Since Python lists are zero-based, we can use the zip built-in function as follows:

    >>> [i for i,j in zip(range(len(haystack)), haystack) if j == 'needle' ]
    

    where "haystack" is the list in question and "needle" is the item to look for.

    (Note: Here we are iterating using i to get the indexes, but if we need rather to focus on the items we can switch to j.)

提交回复
热议问题