【问题标题】:LPTHW ex 40 not working? (Dictionary exercise, does not return key:value pair.)LPTHW ex 40 不工作? (字典练习,不返回键:值对。)
【发布时间】:2017-10-31 22:15:31
【问题描述】:

我对我的代码进行了三次检查,据我所知,它与书中给出的 ex40 基本相同(LPTHW,Python 2.7):

cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'}

cities['NY'] = 'New York'
cities['OR'] = 'Portland'

def find_city(themap, state):
        if state in themap:
            return themap[state]
    else:
        return "Not found."

cities['_find'] = find_city

while True:
    print "State? (ENTER to quit)",
    state = raw_input("> ")

    if not state: break

city_found = cities['_find'](cities, state)
print city_found

预期的输出是这样的:

State? (ENTER to quit) > CA
San Francisco
State? (ENTER to quit) > FL
Jacksonville
State? (ENTER to quit) > O
Not found.
State? (ENTER to quit) > OR
Portland
State? (ENTER to quit) > VT
Not found.
State? (ENTER to quit) >

但是当我运行它时,输入行只是重复,直到我在空白行上按回车,从不产生城市。像这样:

State? (Enter to quit) > KS
State? (Enter to quit) > NY
State? (Enter to quit) > LA
State? (Enter to quit) > CA
State? (Enter to quit) > 
Not found.

谁能告诉我我忽略了什么?

谢谢。

【问题讨论】:

    标签: python python-2.7 dictionary key-value


    【解决方案1】:

    线条

    city_found = cities['_find'](cities, state) # Better: city_found = find_city(cities, state)
    print city_found
    

    需要在 while 循环内,而不是在它之后。

    我完全不明白cities['_find'] = find_city 的目的是什么——为什么不直接调用该函数而不是将其添加到城市字典中呢?对我来说似乎非常不合时宜。

    【讨论】:

    • 谢谢,新页面上的间距在视觉上看起来不同,我没有从行号检查空格。至于不直接调用函数,我认为这是教学法,展示了如何将函数构建到字典中。
    • @themagicbean 这很有道理,但老实说,这是一个糟糕的例子。将函数放入字典可能很有用,例如当您必须根据上下文动态选择要调用的函数时。但是,您将拥有一个用于函数的字典和另一个用于数据的字典。把这些东西混在一起是令人困惑的。
    猜你喜欢
    • 1970-01-01
    • 2016-03-31
    • 2018-05-31
    • 2018-11-01
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    • 2014-08-26
    相关资源
    最近更新 更多