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

标签 python python-2.7

我正在尝试做“以艰难的方式学习 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/

相关文章:

Python分解

python - 找不到 Python 代码中的错误

c++ - 在 SWIG 中将结构从 C++ 函数返回到 Python

python-2.7 - 在 python scikit-learn 中,RBF 内核的性能比 SVM 中的线性性能差得多

python - YouTube API Python upload_video.py从脚本而不是命令行运行

python - 机器学习 - 大数据集的问题

python - 如何在我的 Cloud-Run Flask 应用程序中获取用户的 IP 地址?

python - Abaqus/Python 从 csv 文件读取 MappedField 数据

python - 在 Python 中解析文件时跳过一行?有什么简单/基本的方法吗?

python - 在三元运算符中模拟传递?