接下来我要教你另外一种让你伤脑筋的容器型数据结构,因为一旦你学会这种容器,你将拥有超酷的能力。这是最有用的容器:字典(dictionary)。

    Python 将这种数据类型叫做 “dict”,有的语言里它的名称是 “hash”。这两种名字我都会用到,不过这并不重要,重要的是它们和列表的区别。你看,针对列表你可以做这样的事情:

1 >>> things = ['a', 'b', 'c', 'd']
2 >>> print things[1]
3 b
4 >>> things[1] = 'z'
5 >>> print things[1]
6 z
7 >>> print things
8 ['a', 'z', 'c', 'd']
9 >>>

    你可以使用数字作为列表的索引,也就是你可以通过数字找到列表中的元素。而 dict 所作的,是让你可以通过任何东西找到元素,不只是数字。是的,字典可以将一个物件和另外一个东西关联,不管它们的类型是什么,我们来看看:

 1 >>> stuff = {'name': 'Zed', 'age': 36, 'height': 6*12+2}
 2 >>> print stuff['name']
 3 Zed
 4 >>> print stuff['age']
 5 36
 6 >>> print stuff['height']
 7 74
 8 >>> stuff['city'] = "San Francisco"
 9 >>> print stuff['city']
10 San Francisco
11 >>>

    你将看到除了通过数字以外,我们还可以用字符串来从字典中获取 stuff ,我们还可以用字符串来往字典中添加元素。当然它支持的不只有字符串,我们还可以做这样的事情:

 1 >>> stuff[1] = "Wow"
 2 >>> stuff[2] = "Neato"
 3 >>> print stuff[1]
 4 Wow
 5 >>> print stuff[2]
 6 Neato
 7 >>> print stuff
 8 {'city': 'San Francisco', 2: 'Neato',
 9     'name': 'Zed', 1: 'Wow', 'age': 36,
10     'height': 74}
11 >>>

    在这里我使用了两个数字。其实我可以使用任何东西,不过这么说并不准确,不过你先这么理解就行了。

    当然了,一个只能放东西进去的字典是没啥意思的,所以我们还要有删除物件的方法,也就是使用 del 这个关键字:

1 >>> del stuff['city']
2 >>> del stuff[1]
3 >>> del stuff[2]
4 >>> stuff
5 {'name': 'Zed', 'age': 36, 'height': 74}
6 >>>

    接下来我们要做一个练习,你必须非常仔细,我要求你将这个练习写下来,然后试着弄懂它做了些什么。这个练习很有趣,做完以后你可能会有豁然开朗的感觉。

 1 cities = {'CA': 'San Francisco', 'MI': 'Detroit',
 2                      'FL': 'Jacksonville'}
 3 
 4 cities['NY'] = 'New York'
 5 cities['OR'] = 'Portland'
 6 
 7 def find_city(themap, state):
 8     if state in themap:
 9         return themap[state]
10     else:
11         return "Not found."
12 
13 # ok pay attention!
14 cities['_find'] = find_city
15 
16 while True:
17     print "State? (ENTER to quit)",
18     state = raw_input("> ")
19 
20     if not state: break
21 
22     # this line is the most important ever! study!
23     city_found = cities['_find'](cities, state)
24     print city_found
View Code

相关文章:

  • 2021-11-09
  • 2021-04-21
  • 2021-12-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-24
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-08
相关资源
相似解决方案