[英]Python: List Comprehension with a Nested Loop
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? 什么是实现此目的的Python方法? 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. 提前致谢。
您可以对该命令使用内置的any
函数[item for item in some_list if any(s in item for s in string)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.