我有一個字串 ORIGINAL = 'ready' 和一個 word_list = ['error', 'radar', 'brave']。我使用嵌套的 forloop 來檢查 word_list 中每個單詞的每個字母是否在 ORIGINAL 中。如果為True,則將字母修改為“*”,否則復制該字母。這里是棘手的部分,比如說'error',第一個'r'在'error'里面,我怎樣才能停止forloop并移動到下一個不重復的字母?下面是我的代碼。需要幫助!謝謝。這實際上是 WORDLE 背后演算法的一部分。
ORIGINAL = 'ready'
word_list = ['error', 'radar', 'brave']
result, modified_list = [], []
for word in word_list:
for i in range(len(word)):
if word[i] in ORIGINAL:
l = '*'
else:
l = word[i]
result.append(l)
modified_list.append(''.join(result))
result.clear()
print(modified_list)
輸出:
['***o*', '*****', 'b**v*']
期望的輸出:
['**ror', '***ar', 'b**v*']
uj5u.com熱心網友回復:
您可以跟蹤ORIGINAL已經看到的字母。
ORIGINAL = 'ready'
word_list = ['error', 'radar', 'brave']
result, modified_list = [], []
for word in word_list:
seen = []
for i in range(len(word)):
if word[i] in ORIGINAL and word[i] not in seen:
l = '*'
seen.append(word[i])
else:
l = word[i]
result.append(l)
modified_list.append(''.join(result))
result.clear()
print(modified_list)
uj5u.com熱心網友回復:
您可以ORIGINAL在word_list. 然后,使用str.replace及其可選引數count來修改 ORIGINAL 的副本,并通過洗掉匹配的字母來避免重復字母問題:
for word in word_list:
temp_original = ORIGINAL # Create a copy of ORIGINAL
for i in range(len(word)):
if word[i] in temp_original: # Lookup the copy of ORIGINAL
...
temp_original = temp_original.replace(word[i], "", 1) # Remove the seen letter from your copy of ORIGINAL
...
結果代碼:
ORIGINAL = 'ready'
word_list = ['error', 'radar', 'brave']
result, modified_list = [], []
for word in word_list:
temp_original = ORIGINAL
for i in range(len(word)):
if word[i] in temp_original:
l = '*'
temp_original = temp_original.replace(word[i], "", 1)
else:
l = word[i]
result.append(l)
modified_list.append(''.join(result))
result.clear()
輸出:
['**ror', '***ar', 'b**v*']
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/436053.html
