在数据结构上进行迭代时,不要删除其中的项。
在这种情况下,请注意您正在从字典中删除,因为您不想随机选择同一个单词两次。更好的方法(迭代时不需要删除元素)是
将字典转换为元组列表,洗牌该列表,然后迭代该列表。
这让我们可以选择一个随机生成的单词,而不必担心选择同一个单词两次。
下面是一段代码片段,展示了如何实现这一点:
import random
words = [('key1', 'val1'), ('key2', 'val2'), ('key3', 'val3')]
random.shuffle(words)
for word, translated_word in words:
user_translation = input(f"what is the translation for {word}?")
# Remember that .replace() does not modify the original string,
# so we need to explicitly assign its result!
user_translation = user_translation.replace("'", "")
if user_translation == translated_word:
print('Correct!')
else:
print('Incorrect.')