gpt4 book ai didi

python 下划线 : learn python the hard way exercise 40

转载 作者:行者123 更新时间:2023-11-28 19:45:21 25 4
gpt4 key购买 nike

我正在尝试做“以艰难的方式学习 Python”一书中的练习:第 106 页。示例如下:

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

我不明白 cities['_find'] = find_city 是做什么的?什么是 _find?特别是,为什么下划线?同样,我不确定 city_found = cities['_find'](cities, state) 做了什么。我在同一个问题上看到了类似的帖子: learn python the hard way exercise 40 help

基本上是说 cities['_find'] = find_city 将函数 find_city 添加到字典中,但我仍然不明白 city_found = cities['_find'](cities,状态) 做(?)

如果有人能向我解释以上两行,我将不胜感激。感谢您的宝贵时间。

最佳答案

这段代码:

cities['_find'] = find_city

使用键 _find 简单地将函数 find_city 插入到 cities 字典中。下划线没有特别的意义,它只是关键字符串的一部分。可能选择不与实际城市名称冲突。

这段代码:

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

调用 find_city 函数,首先使用 _find 键在字典中查找它。

可以改写为:

city_found = find_city(cities, state)

这样做似乎没有任何真正的,让字典(在代码中称为“ map ”)包含没有任何好处find 函数,我可以看到。

关于python 下划线 : learn python the hard way exercise 40,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10716916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com