我有以下代碼運行良好
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")
uj5u.com熱心網友回復:
首先,避免使用像“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)]
uj5u.com熱心網友回復:
any在 python 中,您可以查看串列中的元素是否滿足條件。如果是,則回傳 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])
uj5u.com熱心網友回復:
首先,請不要使用“串列”作為變數。有一個名為 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")
uj5u.com熱心網友回復:
由于非空串列測驗為 True(例如if [1]: print('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'
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/367980.html
上一篇:為什么冒泡排序需要兩個回圈?
下一篇:單擊時如何使精靈消失?
