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

看板Python作者 (鋒仔)時間5年前 (2019/06/12 16:29), 編輯推噓4(407)
留言11則, 3人參與, 5年前最新討論串3/5 (看更多)
※ 引述《a172545056 (Leon)》之銘言: : 各位前輩大家好,我是剛接觸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”, : 跟我想要的結果不太一樣, : 想了很久不知道該怎麼做 : 還請各位前輩指點一下,謝謝! 目前想到最有效率的寫法 ListA=["Apple","food","Iron"] ListB=["x","z","on"] ListC=["No","No","No"] for i in range(len(ListA)): if ListB[i] in ListA[i]: ListC[i] = "Yes" print(ListC) -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 59.115.96.208 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1560328154.A.251.html

06/12 20:45, 5年前 , 1F
如果要少行一點
06/12 20:45, 1F

06/12 20:45, 5年前 , 2F
ListC=[]
06/12 20:45, 2F

06/12 20:51, 5年前 , 3F
for idx, (a, b) in enumerated(zip(ListA,ListB)):
06/12 20:51, 3F

06/12 20:51, 5年前 , 4F
if b in a:
06/12 20:51, 4F

06/12 20:51, 5年前 , 5F
ListC.append('Yes')
06/12 20:51, 5F

06/12 20:51, 5年前 , 6F
else:
06/12 20:51, 6F

06/12 20:51, 5年前 , 7F
ListC.append('No')
06/12 20:51, 7F

06/13 09:21, 5年前 , 8F
謝謝兩位前輩指點!
06/13 09:21, 8F

06/13 10:07, 5年前 , 9F
zip 應該是比較直覺的解,不懂為什麼要 enumerated
06/13 10:07, 9F

06/13 10:07, 5年前 , 10F
for a, b in zip(ListA, ListB):
06/13 10:07, 10F

06/14 14:25, 5年前 , 11F
對...不小心多放了enumerate
06/14 14:25, 11F
文章代碼(AID): #1T0BVQ9H (Python)
討論串 (同標題文章)
文章代碼(AID): #1T0BVQ9H (Python)