简体   繁体   中英

How to find the index of an item in a list, but not an exact match

I have a list something like this:

ls = ['item1', 'this is item2', 'item3']

I want to be able to find the index of the item 'this is item2' by searching for 'item2' . The index function is looking for the exact match so it wouldn't help here:

index = ls.index('item2')

How can I achieve this requirement?

Here's a solution using next with a generator, and enumerate to get the index:

>>> ls = ['item1', 'this is item2', 'item3']
>>> next(i for i, v in enumerate(ls) if 'item2' in v)
1

It will raise StopIteration if the item is not found. If you want None or -1 instead, you can give it as the second argument to next :

>>> next((i for i, v in enumerate(ls) if 'item5' in v), -1)
-1

You may simply pass by a temporary list and apply index method on it:

ls = ['item1', 'this is item2', 'item3']
index = ['item2' in item for item in ls].index(True)

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