代码之家  ›  专栏  ›  技术社区  ›  Dimitriy Glefa

条件遍历字典

  •  1
  • Dimitriy Glefa  · 技术社区  · 4 年前

    我正在学习python,试图编写一段代码,向用户展示从池中随机选择的单词,并让他为这个单词编写翻译。如果用户正确翻译了这个词,这个词应该从池中删除。

    谢谢你的帮助。

    dic = {
      "key1": "val1",
      "key2": "val2",
      "key3": "val3"
    }
    
    import random
    
    for keys, values in dict(dic).items():
       a = []
       a.append(random.choice(list(dic)))
       translation = input(f"what is the translation for {a}")
       translation.replace("'", "")
       
       if a[0] == translation:
            del dic[keys]
    

    这是我写的代码,但即使出现这种情况,这个词也不会从池中删除。

    1 回复  |  直到 4 年前
        1
  •  0
  •   BrokenBenchmark Miles Budnek    4 年前

    在数据结构上进行迭代时,不要删除其中的项。

    在这种情况下,请注意您正在从字典中删除,因为您不想随机选择同一个单词两次。更好的方法(迭代时不需要删除元素)是 将字典转换为元组列表,洗牌该列表,然后迭代该列表。 这让我们可以选择一个随机生成的单词,而不必担心选择同一个单词两次。

    下面是一段代码片段,展示了如何实现这一点:

    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.')