如何判断列表中任一元素是否存在于长字符串中?
解决方法
你可以直接使用Python内置的any()函数,它会遍历可迭代对象,只要其中有一个元素为True就返回True,完美匹配你的需求:
aa=["column","is","the","word","others", "excludition"] bb="from the long text" result = any(wd in bb for wd in aa) print(result) # 输出: True
补充说明
any()接收一个可迭代对象(这里用生成器表达式wd in bb for wd in aa,比列表推导式更省内存,因为不需要生成完整的列表)。- 一旦找到第一个存在于字符串中的元素,
any()就会停止遍历,效率更高。
如果不想用内置函数,也可以手动实现循环判断:
aa=["column","is","the","word","others", "excludition"] bb="from the long text" result = False for wd in aa: if wd in bb: result = True break # 找到后立即退出循环,提升效率 print(result) # 输出: True
内容的提问来源于stack exchange,提问作者user3373877
相关产品推荐
相关产品推荐

