简体   繁体   中英

Find item in list by type

I have a list that can contain several elements of different types. I need to check if in this list there is one or more elements of a specific type and get its index.

l = [1, 2, 3, myobj, 4, 5]

I can achieve this goal by simply iterate over my list and check the type of each element:

for i, v in enumerate(l):
  if type(v) == Mytype:
    return i

Is there a more pythonic way to accomplish the same result?

You can use next and a generator expression :

return next(i for i, v in enumerate(l) if isinstance(v, Mytype)):

The advantage of this solution is that it is lazy like your current one: it will only check as many items as are necessary.

Also, I used isinstance(v, Mytype) instead of type(v) == Mytype because it is the preferred method of typechecking in Python. See PEP 0008 .

Finally, it should be noted that this solution will raise a StopIteration exception if the desired item is not found. You can catch this with a try/except, or you can specify a default value to return:

return next((i for i, v in enumerate(l) if isinstance(v, Mytype)), None):

In this case, None will be returned if nothing is found.

You can use list comprehension.

Get all elements of type string:

b = [x for x in a if isinstance(x,str)]

Get all indexes of elements of type string:

b = [x[0] for x in enumerate(a) if isinstance(x[1],str)]

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