首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在python2.7中从字典返回正确的项

在python2.7中从字典返回正确的项
EN

Stack Overflow用户
提问于 2016-04-13 10:25:19
回答 1查看 39关注 0票数 0

我刚刚开始学习Python,作为一个有趣的练习,一个朋友让我写一个程序:从一个单独的文件中随机选取一个关键字,将所选的关键字与字典中的关键字进行比较,然后打印一个包含关键字和附加信息的字符串(我们称之为“定义”)。它应该取一个词,通过在前面加上辛辛那提这个词,把它变成委婉语,然后给出定义。我写的代码如下所示。

代码语言:javascript
复制
    import random

    def cincinnati_word():
        list = open("cincinnati_stuff.txt").read().splitlines()
        word = random.choice(list)
        return word

    cincinnati_dict = {
        'car wash': 'you slip and slide through the legs of at least three hookers while they pee on you',
        'sweat sock': 'you get your whole foot into an orifice on someone else\'s body. Gettin\' in above the ankle makes it a tube sock',
        'hot pocket': 'you stick a lit firecracker into someone\'s pocket',
        'rest home': 'they make the dog chow',
        'Eggo waffle': 'you\'re having sex with someone and you press a tennis racket over his/her face and scream "Leggo my Eggo!"',
        'slip \'n slide': 'a kid throws up in the hallway at school',
        'dust mop': 'you don\'t trim your pubic hair at all',
        'prom date': 'a hooker agrees to the barter system of payment',
        'double dip': 'you get two VD\'s from the same partner at the same time',
        'dog park': 'the PETA shelter throws all the carcasses of the dogs they put down',
        'soda stream': 'you fart into someone\'s drink through a straw',
        'gramophone': 'someone blows a trumpet real loud in your ear',
        'tail pipe': 'you put a gerbil up your butt with a paper towel roll',

    }


    for word, meaning in cincinnati_dict.items():
        word = cincinnati_word()
        new_word = cincinnati_dict.get(word)
        if new_word:
            print "The Cincinnati Kid: \"The old Cincinnati %s, yeah, that's where %s.\"" % (word, meaning)
            break
        else:
            print "The Cincinnati Kid: \"The Cincinnat %s? That ain't no thing I ever hoid of." %(word)
        break

给我带来麻烦的是这段代码能正常工作...差不多了。它成功地从文本文件中检索到一个关键字。它成功地将其与字典中的键列表进行了比较。它还成功地从字典中返回一个定义。问题是,无论使用哪个关键字,返回的定义都是相同的。到目前为止,在我运行的每个测试中,它总是返回辛辛那提留声机的定义。

我相信答案是显而易见的,但我已经盯着这个看了几天了,我看不出是什么导致了这一点。有人能给点建议吗?我要提前表示感谢。

EN

回答 1

Stack Overflow用户

发布于 2016-04-13 11:00:22

在不需要的时候使用循环(for word, meaning in cincinnati_dict:)。无条件的break是一个提示,你根本不想要循环。

相反,只要在get调用和if条件中使用meaning而不是new_word

代码语言:javascript
复制
word = cincinnati_word() 
meaning = cincinnati_dict.get(word)
if meaning:
    print "The Cincinnati Kid: \"The old Cincinnati %s, yeah, that's where %s.\"" % (word, meaning)
else:
    print "The Cincinnati Kid: \"The Cincinnati %s? That ain't no thing I ever hoid of." %(word)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36587448

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档