为什么我得到这个关键错误?

2024-04-28 02:55:38 发布

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

{1$我不知道怎么回事?在

campers = {'pb' : 'Pooder Bennet', 'jf' : 'Jupiter Fargo',
           'rb' : 'Randy Buffet', 'bl' : 'Botany Lynn',
       'bt' : 'Boris Tortavich', 'tn' : 'Trinda Noober',
       'fj' : 'Freetus Jaunders', 'nt' : 'Ninar Tetris', 
       'gm' : 'Gloobin Marfo', 'nk' : 'Niche Kaguya',
       'bd' : 'Brent Drago', 'vt' : 'Volga Toober',
       'kt' : 'Kinser Talebearing', 'br' : 'Bnola Rae',
       'nb' : 'Nugget Beano', 'yk' : 'Yeldstat Krong',
       'gy' : 'Gelliot Yabelor', 'il' : 'Illetia Dorfson',
       'ct' : 'Can Tabber', 'tv' : 'Trinoba Vyder'}

    campers_outside_theater = random.sample(campers.keys(), 5)
    people = campers_outside_theater + ['Troid, the counselor from the bus.']
    choices = '\n\n'.join('%d. %s' % (i + 1, campers[p]) for (i, p) in enumerate(people))

Tags: thepeoplebuffetjupiterpbblrbjf
2条回答

这将为您提供您想要的:

import random
campers = {'pb' : 'Pooder Bennet', 'jf' : 'Jupiter Fargo',
           'rb' : 'Randy Buffet', 'bl' : 'Botany Lynn',
       'bt' : 'Boris Tortavich', 'tn' : 'Trinda Noober',
       'fj' : 'Freetus Jaunders', 'nt' : 'Ninar Tetris', 
       'gm' : 'Gloobin Marfo', 'nk' : 'Niche Kaguya',
       'bd' : 'Brent Drago', 'vt' : 'Volga Toober',
       'kt' : 'Kinser Talebearing', 'br' : 'Bnola Rae',
       'nb' : 'Nugget Beano', 'yk' : 'Yeldstat Krong',
       'gy' : 'Gelliot Yabelor', 'il' : 'Illetia Dorfson',
       'ct' : 'Can Tabber', 'tv' : 'Trinoba Vyder'}

campers_outside_theater = random.sample(campers.keys(), 5)
people = campers_outside_theater #+ ['Troid, the counselor from the bus.']
choices = '\n\n'.join('%d. %s' % (i + 1, campers[p]) for (i, p) in enumerate(people))
print(choices)

你有keys(people),但没有这样的动物-这是你的第一个错误。它不是KeyError,而是NameError(因为keys从未定义)。然后,当我删除了键并得到enumerate(people)时,你得到了一个实际的键错误,因为你试图用'Troid, the counselor from the bus.'作为键。。。但它不是一个。我假设你想把他包括在车上的人中,但你必须用另一种方式。也许把他包括在你的露营者字典里,在你随机抽取样本后,总是把他加到你的钥匙里。在

这一行是导致错误的原因:

choices = '\n\n'.join('%d. %s' % (i + 1, campers[p]) for (i, p) in enumerate(people))

原因就在于这一行:

^{pr2}$

字典campers中没有名为Troid, the counselor from the bus.

要解决此问题:

>>> campers.update([('Troid', 'the counselor from the bus.')])

相关问题 更多 >