-5

我正在阅读 zed shaw 的书“Learning python the hard way”。原谅我,但我是编码新手,我很难理解这一点。我似乎看不到 find_city 函数如何通过输入状态找出要返回的城市。带有“好吧注意”和“#这条线是最重要的!学习!是那些让我感到困惑的线。

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."

# ok pay attention!
cities['_find'] = find_city

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

    if not state: break

    # this line is the most important ever! study!
    city_found = cities['_find'](cities, state)
    print city_found
4

1 回答 1

2

简要地:

  • cities被实例化为字典,并在此处插入一些键/值。键和值都是 CA -> San Francisco, MI -> Detroit 等的字符串。

  • 定义了一个名为的函数find_city,它接受两个输入参数(themapstate);

  • cities字典中添加了另一个键/值,其中键是字符串“_find”,但是这一次,值是函数 find_city 而不是以前的字符串;

  • city_found = cities['_find'](cities, state)您向字典询问与cities键“_find”关联的值的行中,即函数find_city。然后,调用此函数,字典本身作为第一个参数,stdin 读取的“状态”作为第二个参数。

如果它被写成这样,它会是一样的:

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

高温高压

于 2012-05-11T14:04:47.360 回答