简体   繁体   中英

Is there a way to find index of "in" keyword match in python

The title of this post is probably pretty vague. Here is what I need to know

If I use something like

if x in list

how do I find the index in the list where a match occurs?

You can't get that from in itself. For lists, you can use the index method:

>>> [1, 2, 5, 8, -1, 2].index(2)
1

This will raise an exception if the item is not in the list. Note that it returns the index of the first occurrence. It might occur multiple times.

You can't.

It's better to use list_.index(x) for this use case.

If there's a match in your sequence zero or multiple times, you should prefer to use enumerate :

>>> list_ = ['foo', 'bar', 'spam', 'foo', 'eggs']
>>> idxs = [i for i,x in enumerate(list_) if x == 'foo']
>>> print idxs
[0, 3]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM