-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))
4

2 回答 2

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),但没有这样的动物——那是你的第一个错误。它不是 a KeyError,而是 a NameError(因为keys从未定义过)。然后,当我删除密钥时,enumerate(people)由于您试图将其'Troid, the counselor from the bus.'用作密钥,因此您遇到了实际的密钥错误……但事实并非如此。我假设你想把他包括在公共汽车上的人中,但你必须以不同的方式做到这一点。也许将他包括在您的露营者字典中,并在您随机抽样后始终将他添加到您的钥匙中。

于 2013-12-04T23:27:56.653 回答
1

此行是导致您的错误的原因:

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

原因是因为这条线:

people = campers_outside_theater + ['Troid, the counselor from the bus.']

字典里没有名字campersTroid, the counselor from the bus.

要解决这个问题:

>>> campers.update([('Troid', 'the counselor from the bus.')])
于 2013-12-04T23:40:15.313 回答