簡體   English   中英

使用列表推導作為 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")

python 中的any允許您查看列表中的元素是否滿足條件。 如果是,則返回 True,否則返回 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])

首先,請不要使用“列表”作為變量。 有一個內置的 function 稱為 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")

由於非空列表測試為 True(例如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)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM