I have a situation where I am using list comprehension to scan one list and return items that match a certain criteria.
[item for item in some_list_of_objects if 'thisstring' in item.id]
I want to expand this and have a list of things that can be in the item, the list being of unknown length. Something like this:
string_list = ['somestring', 'another_string', 'etc']
[item for item in some_list_of_objects if one of string_list in item.id]
What is a pythonic way to accomplish this? I know I could easily rewrite it to use the standard loop structure, but I would like to keep the list comprehension if I can do so without producing very ugly code.
Thanks in advance.
Use any :
string_list = ['somestring', 'another_string', 'etc']
[item for item in some_list if any(s in item.id for s in string_list)]
any will lazily evaluate breaking on the first match or checking all if we don't get a match.
您可以对该命令使用内置的any
函数[item for item in some_list if any(s in item for s in string)]
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.