1

我有一个字符串 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*']

4

2 回答 2

1

您可以ORIGINALword_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*']
于 2022-03-01T02:46:35.543 回答
1

您可以跟踪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)
于 2022-03-01T02:47:11.753 回答