使用列表理解作为 if else 语句的条件

Using list comprehension as condition for if else statement

我有以下代码,效果很好

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")

any in python 允许您查看列表中的元素是否满足条件。如果是这样 returns True else False.

if any("test" in s for s in list): # Returns True if "test" in a string inside list
    print([s for s in list if "test" in s])

首先,请不要使用“列表”作为变量。有一个名为 list() 的内置函数...

可以这样工作:

list_ = ["age", "test=53345", "anotherentry", "abc"]
val = [s for s in list_ if "test" in s]                #filters your initial "list_" according to the condition set

if val:
    print(val)                                         #prints every entry with "test" in it
else:
    print("None of the searched words found")

由于非空列表测试为真(例如 if [1]: print('yes') 将打印 'yes'),您可以只查看您的理解是否为空:

>>> alist = ["age", "test=53345", "anotherentry", "abc"]
>>> find = 'test anotherentry'.split()
>>> for i in find:
...   if [s for s in alist if i in s]:i
...
'test'
'anotherentry'

但是因为找到一个事件就足够了,所以使用 any 会更好:

>>> for i in find:
...   if any(i in s for s in alist):i
...
'test'
'anotherentry'

首先,避免使用“list”等保留字来命名变量。 (保留字总是标记为蓝色)。

如果您需要这样的东西:

mylist = ["age", "test=53345", "anotherentry", "abc"]
keywords = ["test", "anotherentry", "zzzz"]
    
    for el in mylist:
        for word in words:
            if (word in el):
                print(el)

使用这个:

[el for word in keywords for el in mylist if (word in el)]