第七章 映像和集合类型
字典
1、字典是python中唯一的映射类型。映像类型中的数据是无序排列的。字典是作为可变的哈系表实现的。
2、字典操作
创建字典
访问字典
dict = {'name':'joe','age':22,'sex':'male'}
for key in dict:
print "%r : %r \n" % (key,dict[key])
'age' : 22
'name' : 'joe'
'sex' : 'male'
相关函数:
dict() dict.copy() 函数,这里是浅拷贝。
len() 返回键值对的数目。
hash()返回是否可以当作主键。
>>> dict
{'age': 22, 'name': 'joe', 'sex': 'male'}
>>> dictcp = dict(dict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable
>>> dictcp = dict
>>> dictcp
{'age': 22, 'name': 'joe', 'sex': 'male'}
>>> dictcp['name'] = 'lw'
>>> dictcp
{'age': 22, 'name': 'lw', 'sex': 'male'}
>>> dict
{'age': 22, 'name': 'lw', 'sex': 'male'}
>>> dict0 = dict.copy()
>>> dict0
{'age': 22, 'name': 'lw', 'sex': 'male'}
>>> dict0['name'] = 'han'
>>> dict
{'age': 22, 'name': 'lw', 'sex': 'male'}
>>> dict0
{'age': 22, 'name': 'han', 'sex': 'male'}
>>> del dict
>>> dict8 = dict(dict0)
>>> dict0
{'age': 22, 'name': 'han', 'sex': 'male'}
>>> dict8['name'] = 'lw'
>>> dict0
{'age': 22, 'name': 'han', 'sex': 'male'}
>>> dict8
{'age': 22, 'name': 'lw', 'sex': 'male'}
>>>
**注意:**TypeError: ‘dict’ object is not callable这个异常是由于我定义的字典名称与函数名冲突。
解决办法就是del dict 删除冲突的字典名就好了。
3、内建函数
keys() values() items() (最后一个返回元组的列表)
以上方法在不顺序访问字典时十分有用。
sorted()函数用来顺序遍历,按照键值排序
update() 两个字典的更新。相同键的元素值覆盖,不同的添加进去。eg:dict2.update(dict3)
clear()删除所有条目。
集合
1、集合的创建:使用集合的工厂方法 以及type len 方法。分为可变集合和不可变集合。最重要的就是不会存在重复元素,这也是集合的特性。
>>> s = set("cheese")
>>> s
set(['h', 'c', 'e', 's'])
>>> ss = frozenset("cheese")
>>> ss
frozenset(['h', 'c', 'e', 's'])
>>> type(s)
<type 'set'>
>>> len(s)
4
>>>
2、访问集合
>>> for i in s:
... print i
h
c
e
s
>>>
3、更新集合
>>> s.add('z')
>>> s
set(['h', 'c', 'z', 'e', 's'])
>>> s.add(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> s.add(2)
>>> s
set([2, 'e', 'h', 'c', 's', 'z'])
>>> s.update("liwng")
>>> s
set([2, 'e', 'g', 'i', 'h', 'c', 'l', 's', 'n', 'w', 'z'])
>>> s.remove(2)
>>> s
set(['e', 'g', 'i', 'h', 'c', 'l', 's', 'n', 'w', 'z'])
>>>