Skip to main content
 首页 » 编程设计

python之如何检查python中包含的列表中的项目

2025年05月04日15lyhabc

我有 2 个列表,

my_list = ['on@3','one',"$", "lo#"] 
spl = ["@","$"] 

我正在尝试获取“my_list”中的项目,其中包含 spl 中的任何项目。

我试过了

out_list = [item for item in my_list if item.contains("!".join(spl))] 

但这会产生错误。

我的预期输出是

out_list = ["on@3","$"] 

请您参考如下方法:

没有item.contains这样的方法.有 item.__contains__ ,但您不需要直接调用它。

您想检查 spl 中是否有任何项包含在项目中,使用内置 any :

lst = [item for item in my_list if any(x in item for x in spl)] 
# ...                           if any(item.__contains__(x) for x in spl)] 
print(lst) 
# ['on@3', '$']