学习python艰难的方式锻炼40帮助

时间:2011-03-25 15:41:23

标签: python

嘿伙计们,我无法理解这一点,当地图被真正引用到城市时,我不明白。或者最后一行,(城市,州)部分是什么?

感谢。

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

1 个答案:

答案 0 :(得分:9)

cities['_find']正是find_city。因此cities['_find'](cities, state)find_city(cities, state)相同。

我的第一个陈述的原因是这一行:

cities['_find'] = find_city

那不会调用find_city,它会将函数本身粘贴在字典中。 Python函数只是列表和类实例之类的对象。如果你没有在括号后加上括号,可以将它们分配给变量。