[英]How to check if two elements at the same number index in different strings match?
假設兩個長度相等的字符串,如何檢查相同數字索引處的元素是否匹配? 例如,我想檢查部分猜中的單詞('ap_le')中的字母是否與完整單詞('apple')中相同索引處的字母匹配。 因此,在該示例中,function 理想情況下會返回 True。
但是,我沒有收到任何 output,我相信問題可能在於:if mw[ltr] == ow[ltr]。 我通過 pythontutor 運行它,它說這里有語法錯誤,我不確定如何檢查元素和索引的相同性。
import string
def match_with_gaps(guess, correct_word):
g = list(guess.replace(' ',''))
cw = list(correct_word)
indices = [idx for idx, x in enumerate(g) if x in string.ascii_lowercase]
for ltr in indices:
if g[ltr] == cw[ltr]:
return True
return False
match_with_gaps('ap_ le', 'apple')
您只是在語法錯誤的 if 語句中缺少一個冒號。 我不確定mw
或ow
來自哪里,但我會使用上面列表中的變量,然后翻轉邏輯以在不匹配時返回 false,僅在所有indices
匹配時返回True
。 嘗試這個:
import string
def match_with_gaps(guess, correct_word):
g = list(guess.replace(' ',''))
cw = list(correct_word)
indices = [idx for idx, x in enumerate(g) if x in string.ascii_lowercase]
for index in indices:
if g[index] != cw[index]:
return False
return True
match_with_gaps('ap_ le', 'apple')
編碼愉快!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.