【发布时间】:2021-11-27 20:37:08
【问题描述】:
我有以下运行良好的代码
list = ["age", "test=53345", "anotherentry", "abc"]
val = [s for s in list if "test" in s]
if val != " ":
print(val)
但我想要做的是使用列表推导作为 if else 语句的条件,因为我需要证明多个单词的出现。知道它不起作用,我正在寻找这样的东西:
PSEUDOCODE
if (is True = [s for s in list if "test" in s])
print(s)
elif (is True = [l for l in list if "anotherentry" in l])
print(l)
else:
print("None of the searched words found")
【问题讨论】:
-
这里不需要列表理解,因为你没有理解列表,只是想写一个聪明的单行
-
"if val != " "" but
val是一个列表...这就是列表推导的作用,也是它们的目的,它们使用映射创建列表 /filtering 对可迭代对象的操作。val将永远等于字符串 -
这个问题不是很清楚。您是否有单词列表,并想检查其中是否包含某些单词?
-
从 Python 3.8 开始,您拥有“海象”运算符
:=。这个问题不是很清楚,但也许这就是你要找的?if(sl := [s for s in list if "test" in s]): print(sl)
标签: python if-statement list-comprehension