如何将列表推导式作为if else语句的条件实现多关键词判断
正确实现方案
Python 中空列表的布尔值为 False,非空列表的布尔值为 True,你可以直接利用这个特性,结合海象运算符(Python 3.8+ 支持)实现需求,避免重复遍历列表,代码如下:
# 注意不要用 list 作为变量名,会覆盖 Python 内置的 list 类型 my_list = ["age", "test=53345", "anotherentry", "abc"] if match_val := [s for s in my_list if "test" in s]: print(match_val) elif match_val := [s for s in my_list if "anotherentry" in s]: print(match_val) else: print("None of the searched words found")
兼容 Python 3.8 以下版本的写法
如果你的运行环境不支持海象运算符,可以直接把列表推导式作为判断条件,仅会多执行一次列表遍历,逻辑依然成立:
my_list = ["age", "test=53345", "anotherentry", "abc"] if [s for s in my_list if "test" in s]: print([s for s in my_list if "test" in s]) elif [s for s in my_list if "anotherentry" in s]: print([s for s in my_list if "anotherentry" in s]) else: print("None of the searched words found")
多关键词场景优化写法
如果需要校验的关键词数量较多,建议把关键词按优先级存入列表循环判断,扩展性更高:
my_list = ["age", "test=53345", "anotherentry", "abc"] # 关键词按判断优先级排序,靠前的优先匹配 check_keywords = ["test", "anotherentry"] for kw in check_keywords: match_res = [s for s in my_list if kw in s] if match_res: print(match_res) break else: # 所有关键词都没有匹配结果时执行 print("None of the searched words found")
原有代码问题说明
你原有代码中的判断条件 if val != " " 存在逻辑错误:val 是列表类型,永远不可能等于空格字符串,代码能正常运行实际是依赖了空列表为 False 的特性,正确写法应该是直接写 if val:。
内容的提问来源于stack exchange,提问作者plategt
相关产品推荐
相关产品推荐

