python3 _笨方法学Python_日记_DAY7

习题 40: 字典, 可爱的字典

回顾一下列表:

列表可以通过数字,从0开始的数字来索引列表中的元素

而字典dict,可以通过任何东西找到元素,可以将一个东西和另一个相关联

 

 还可以通过字符串向字典中添加

stuff = {'name': 'Zed', 'age': 18, 'height': 6**6}
stuff['city'] = 'San Francisco'
print(stuff['city'])
stuff[1] = 'Wow'
stuff[2] = 'Neato'
print(stuff)
San Francisco
{'name': 'Zed', 'age': 18, 'height': 46656, 'city': 'San Francisco', 1: 'Wow', 2: 'Neato'}

通过del来删除

stuff = {'name': 'Zed', 'age': 18, 'height': 6**6}
stuff['city'] = 'San Francisco'
print(stuff['city'])
stuff[1] = 'Wow'
stuff[2] = 'Neato'
print(stuff)

del stuff['city']
del stuff[1]
del stuff[2]
print(stuff)
San Francisco
{'name': 'Zed', 'age': 18, 'height': 46656, 'city': 'San Francisco', 1: 'Wow', 2: 'Neato'}
{'name': 'Zed', 'age': 18, 'height': 46656}

 

练习:

cities = {'CA': 'San Francisco', 'MI': 'Detroit',
          'EL': 'Jacksonville'}

cities['NY'] = 'New York'
cities['OR'] = 'Portland'

def find_city(themap, state):
    if state in themap:
        return themap[state]
    else:
        return "Not Found."

cities['_find'] = find_city

while True:
    print("State?(ENTER to quit")
    state = input(">")
    if not state:break

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

结果

State?(ENTER to quit
>YK
Not Found.
State?(ENTER to quit
>NY
New York
State?(ENTER to quit
>OR
Portland
State?(ENTER to quit
>CA
San Francisco
State?(ENTER to quit
>

Process finished with exit code 0

1. Python 看到 city_found = 于是知道了需要创建一个变量。
2. 然后它读到 cities ,然后知道了它是一个字典
3. 然后看到了 ['_find'] ,于是 Python 就从索引找到了字典 cities 中对应的位
置,并且获取了该位置的内容。
4. ['_find'] 这个位置的内容是我们的函数 find_city ,所以 Python 就知道了
这里表示一个函数,于是当它碰到 ( 就开始了函数调用。
5. cities, state 这两个参数将被传递到函数 find_city 中,然后这个函数就被
运行了。
6. find_city 接着从 cities 中寻找 states ,并且返回它找到的内容,如果什么
都没找到,就返回一个信息说它什么都没找到。
7. Python find_city 接受返回的信息,最后将该信息赋值给一开始
city_found 这个变量。

如果你倒着阅读的话,代码可能会变得更容易理解。让我
们来试一下,一样是那行:
1. state city ...
2. 作为参数传递给...
3. 一个函数,位置在...
133
4. '_find' 然后寻找,目的地为...
5. cities 这个位置...
6. 最后赋值给 city_found.
还有一种方法读它,这回是由里向外
1. 找到表达式的中心位置,此次为 ['_find'].
2. 逆时针追溯,首先看到的是一个叫 cities 的字典,这样就知道了 cities
_find 元素。
3. 上一步得到一个函数。继续逆时针寻找,看到的是参数。
4. 参数传递给函数后,函数会返回一个值。然后再逆时针寻找。
5. 最后,我们到了 city_found = 的赋值位置,并且得到了最终结果。



posted @ 2018-03-20 19:02  Mrfri  阅读(272)  评论(0编辑  收藏  举报