感谢。
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
答案 0 :(得分:9)
cities['_find']
正是find_city
。因此cities['_find'](cities, state)
与find_city(cities, state)
相同。
我的第一个陈述的原因是这一行:
cities['_find'] = find_city
那不会调用find_city
,它会将函数本身粘贴在字典中。 Python函数只是列表和类实例之类的对象。如果你没有在括号后加上括号,可以将它们分配给变量。