p在輸出中出現了兩次,因為有apples這個詞。
我試圖修改代碼,使p在輸出中列印一次。謝謝
def in_both(word1, word2)。
for letter in word1:
if letter not in word2。
print (letter)
print(in_both("apples", "oranges")
uj5u.com熱心網友回復:
你需要在一個資料結構中存盤已經看到的字母。在這種情況下,一個set()是最合適的,因為你可以有O(1)查找和添加
def in_both(word1, word2)。
known_letters = set()
for letter in word1:
if letter not in word2 and letter notin known_letters:
print(letter)
known_letters.add(letter)
print(in_both("apples"/span>, "oranges"/span>)
此外,你的代碼將列印一個最終的None,因為它是in_both的回傳值,所以我建議洗掉print呼叫周圍的in_both("apples", "oranges")
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/307305.html
標籤:
上一篇:在Python3.7中,使用rstrip()和lstrip()洗掉字串中的第一個和最后一個下劃線字符"_"會導致字符"t"丟失。
