如何:保留dict中的键,以便在随机选择后继续使用?在翻译器中用值反转键以切换语言?

2024-05-15 20:56:35 发布

您现在位置:Python中文网/ 问答频道 /正文

前提:我是个新手,所以要保持警惕

首先是我有一些问题的代码:

import random
import time

vocabulary = {
    'hola':'hello',
    'adiós':'bye',
    'noche':'night',
    'pronto':'soon'
}

def spa_to_eng():
    already_used = []
    total_attempts = 0
    while len(already_used) < len(vocabulary):
        spa_to_eng = list(vocabulary.keys())
        for key in spa_to_eng:
            key = random.choice(spa_to_eng)
            if key not in already_used:
                print("word to translate:",key)
                answer = input("enter translation: ")
                if answer == vocabulary[key]:
                    print("RIGHT!\n")
                    total_attempts = total_attempts + 1
                    already_used = already_used + [key]
                else:
                    print("NOPE! The right answer is",vocabulary[key].upper(),"\n")
                    total_attempts = total_attempts + 1
                time.sleep(1.5)
            else:
                continue
        break
    print(len(vocabulary),"words done in",total_attempts,"total attempts.")
    print("Effectiveness:",str(int(len(vocabulary)/total_attempts*100))+"%")

spa_to_eng()

现在两个问题我´我想找到解决办法:

1)我的目的是在猜出字典(词汇表)中的所有单词后,将最终结果打破并打印出来。但是,代码有时在尝试2次后停止,有时在尝试3或4次后停止。相反,在跑步结束时,我应该已经完成了4个单词,或者不管它们的数量是多少(这就是“while len(already\u used)”的原因<;len(词汇):“”,根据我的能力,尝试次数不详。在pythontutor.com上进行模拟时,代码似乎跳入了字典,从一个键切换到另一个键,并将一些键标记为已选择的键,因此在尝试2到4次拒绝再次使用它们后,代码停止。简言之:如果我猜到了这个词,就不应该在以后的问题中使用这个词;如果你猜不到,应该一次又一次地问,直到我最后写出正确的译文

2)是否有一个简单的方法来反转键和值的顺序?为了能够从英语翻译成西班牙语,而不是从西班牙语翻译成英语,我想几乎什么都没有改变

抱歉,时间太长了,如果有人帮忙的话,非常感谢。:)


Tags: tokey代码answerinimportleneng
2条回答

您正在初始化主循环中的单词列表spa_to_eng,因此每次调用random.choice(spa_to_eng)时,它都有一个完整的词汇表可供选择。您应该在进入while循环之前初始化列表,然后从列表中删除正确猜测的单词,而不是将它们附加到单独的列表中

def spa_to_eng():
    already_used = []
    total_attempts = 0
    spa_to_eng = list(vocabulary.keys())
    while len(already_used) < len(vocabulary):
        key = random.choice(spa_to_eng)
        if key not in already_used:
            print("word to translate:",key)
            answer = raw_input("enter translation: ")
            if answer == vocabulary[key]:
                print("RIGHT!\n")
                total_attempts = total_attempts + 1
                already_used = already_used + [key]
                spa_to_eng.remove(key)
            else:
                print("NOPE! The right answer is",vocabulary[key].upper(),"\n")
                total_attempts = total_attempts + 1
            time.sleep(1.5)
        else:
            continue
    print(len(vocabulary),"words done in",total_attempts,"total attempts.")
    print("Effectiveness:",str(int(float(len(vocabulary))/total_attempts*100))+"%")

spa_to_eng移出while循环并删除不必要的for循环,可以尝试上面的代码片段吗

第二个

rev_vocabulary = {v: k for k, v in vocabulary.iteritems()}

相关问题 更多 >