[英]elif condition not working properly for string matching in python
我正在開發一個網頁抓取代碼,同時我正在嘗試修改代碼以在網站鏈接具有來自預定義字符串列表的字符串時提取特定元素。 我試圖在 if elif 條件的幫助下做到這一點。
上下文與此類似:
list1 = ["apple","bat"]
list2 = ["cat", "mat"]
tester = ["www.cat.com","www.website.com","www.apple.com"]
for a in tester:
print(a)
if (item1 in a for item1 in list1):
print("apple is present")
elif ("john" in a):
print("failed")
elif (item2 in a for item2 in list2):
print("cat is present")
但問題是匹配沒有正確發生,循環給出了第一個條件的 output,而不是第二個檢查條件。 關於如何克服這種行為的任何建議?
我得到的 Output 是:
apple is present
apple is present
apple is present
如果 if 總是成功而不是 elif,那么問題在於 if 本身,而不是 elif。
在您的情況下,您缺少any
:
if any(item1 in a for item1 in list1):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.