[問題] Python新手 for迴圈問題

作者: a172545056 (Leon)   2019-06-12 09:48:40
各位前輩大家好,我是剛接觸python不久的新人,目前練習到for迴圈時有點卡關,想請
教一下各位前輩
我有三個List
ListA=[“Apple”,“food”,“Iron”]
ListB=[“x”,“z”,“on”]
ListC=[]
今天我想知道ListA中的字串是否有包含ListB的字串,有的話ListC.append(“YES”),沒
有的話ListC.append(“No”),
我想得到的結果是ListC[“No”,“No”,“Yes”]
小弟目前的做法是
for a_str in ListA:
for b_str in ListB:
if b_str in a_str:
ListC.append(“Yes”)
continue
else:
ListC.append(“No”)
這樣子ListC就增加了很多“No”,
跟我想要的結果不太一樣,
想了很久不知道該怎麼做
還請各位前輩指點一下,謝謝!
作者: gt0112   2019-06-12 10:06:00
ab兩個for迴圈就判斷了九次啊
作者: XperiaZ6C (真●安卓輕旗艦)   2019-06-12 10:06:00
不要用for b_str in ListB改if a_str in ListB:
作者: a172545056 (Leon)   2019-06-12 10:28:00
好的 謝謝前輩指點
作者: WayneHong (韋恩咖啡)   2019-06-12 12:51:00
推樓上,直接用in就好
作者: papple23g (逆道者)   2019-06-12 22:42:00
["Yes" if b_str in a_str else "No" for a_str,b_strin zip(ListA,ListB)]
作者: Neptune2901 (NepTrident)   2019-07-06 22:11:00

Links booklink

Contact Us: admin [ a t ] ucptt.com