码迷,mamicode.com
首页 > 编程语言 > 详细

Python的字典和集合

时间:2015-12-24 19:26:07      阅读:293      评论:0      收藏:0      [点我收藏+]

标签:

字典

字典是Python种唯一的映射类型。映射类型中的数据是无序排列的。在映射类型种,我们使用键直接‘映射’到值,这就是为什么叫映射类型的原因,映射类型通常被称做哈希表,因为字典对象就是哈希类型的。
哈希表的算法是获取键,对键执行一个叫做哈希函数的操作,并根据计算的结果,选择在数据结构的某个地址中来存储值。任何一个值存储的地址取决于它的键,因此,哈希表中的值是没有顺序的。哈希表有一个很好的性能,因为用键查询相当快。

字典的基本操作

#字典的赋值
>>> dict1 = {}
>>> dict2 = {‘name‘:‘earth‘,‘port‘:80}
>>> dict1,dict2
({}, {‘name‘: ‘earth‘, ‘port‘: 80})

#使用工厂函数dict()来创建字典
>>> fdict = dict(([‘x‘,1],[‘y‘,2]))
>>> fdict
{‘y‘: 2, ‘x‘: 1}
#访问字典中的值
>>> dict2
{‘name‘: ‘earth‘, ‘port‘: 80}
>>> for key in dict2.keys():
...     print ‘key=%s, value=%s‘ % (key,dict2[key])
... 
key=name, value=earth
key=port, value=80
>>> for key in dict2:
...     print key,dict2[key]
... 
name earth
port 80
#判断字典中是否有某个键
>>> ‘name‘ in dict2
True
>>> dict2.has_key(‘name‘)
True
#更改字典
>>> dict2
{‘name‘: ‘earth‘, ‘port‘: 80}
>>> dict2[‘name‘] = ‘john‘
>>> dict2[‘port‘] = ‘100‘
>>> dict2[‘sex‘] = ‘boy‘
>>> dict2
{‘sex‘: ‘boy‘, ‘name‘: ‘john‘, ‘port‘: ‘100‘}
#删除操作
>>> dict2
{‘sex‘: ‘boy‘, ‘name‘: ‘john‘, ‘port‘: ‘100‘}
>>> del dict2[‘name‘]
>>> dict2
{‘sex‘: ‘boy‘, ‘port‘: ‘100‘}
>>> dict2.clear()
>>> dict2
{}
>>> del dict2
>>> dict2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name ‘dict2‘ is not defined
>>> dict2 = {‘sex‘: ‘boy‘, ‘name‘: ‘john‘, ‘port‘: ‘100‘}
>>> 
>>> dict2.pop(‘name‘)
‘john‘
>>> dict2
{‘port‘: ‘100‘, ‘sex‘: ‘boy‘}
注意:字典的键是不允许改变的,必须是可哈希的。这是因为值是通过键的哈希指定的保存位置,如果键不能哈希就无法保存,如果改变了键,无法从字典种找到值,就会报KeyError。

字典的内建函数

keys():返回一个列表,包含字典种所有的键;values():返回字典所有的值;items():包含所有9(键,值)元组的列表
>>> dict2
{‘port‘: ‘100‘, ‘name‘: ‘jj‘, ‘sex‘: ‘boy‘}
>>> dict2.keys()
[‘port‘, ‘name‘, ‘sex‘]
>>> dict2.values()
[‘100‘, ‘jj‘, ‘boy‘]
>>> dict2.items()
[(‘port‘, ‘100‘), (‘name‘, ‘jj‘), (‘sex‘, ‘boy‘)]
update():将一个字典的内容添加到另一个字典中,如果有键名重复,旧键名所对应的值会被新键名对应的值覆盖。不存在的条目被添加到字典中
>>> dict2
{‘port‘: ‘100‘, ‘name‘: ‘jj‘, ‘sex‘: ‘boy‘}
>>> dict3 = {‘name‘:‘joke‘,‘server‘:‘http‘}
>>> dict2.update(dict3)
>>> dict2
{‘port‘: ‘100‘, ‘server‘: ‘http‘, ‘name‘: ‘joke‘, ‘sex‘: ‘boy‘}
copy():返回一个字典的副本。注意这只是浅复制
>>> dict4 = dict2.copy()
>>> dict4
{‘sex‘: ‘boy‘, ‘port‘: ‘100‘, ‘name‘: ‘joke‘, ‘server‘: ‘http‘}
setdefault():检查字典种是否有某个键,如果有这个键,返回该建对应的值;如果没有键,就为该键赋默认值,并将该键值添加到字典中。该函数会返回该键对应的值
>>> dict3
{‘name‘: ‘joke‘, ‘server‘: ‘http‘}
>>> dict3.setdefault(‘name‘,‘xiaoqiang‘)
‘joke‘
>>> dict3.setdefault(‘port‘,80)
80
>>> dict3
{‘port‘: 80, ‘name‘: ‘joke‘, ‘server‘: ‘http‘}

集合类型

集合对象分为可变集合(set)和不可变集合(frozenset)。可变集合不可哈希,因此不能作为字典的键,也不能做其他集合中的元素。不可变集合恰好相反。

集合的创建和给集合赋值

集合没有特别的语法格式,创建集合的唯一方法:使用集合的工厂函数set()和frozenset()

>>> s = set(‘cheeseshop‘)
>>> s
set([‘c‘, ‘e‘, ‘h‘, ‘o‘, ‘p‘, ‘s‘])
>>> t = frozenset(‘bookshop‘)
>>> t
frozenset([‘b‘, ‘h‘, ‘k‘, ‘o‘, ‘p‘, ‘s‘])
>>> type(s)
<type ‘set‘>
>>> type(t)
<type ‘frozenset‘>

如何访问集合中的值

可以遍历查看集合中的值或检查某项元素是否是一个集合的成员

>>> s
set([‘c‘, ‘e‘, ‘h‘, ‘o‘, ‘p‘, ‘s‘])
>>> t
frozenset([‘b‘, ‘h‘, ‘k‘, ‘o‘, ‘p‘, ‘s‘])
>>> ‘k‘ in s
False
>>> ‘k‘ in t
True
>>> for i in s:
...     print i
... 
c
e
h
o
p
s

更新集合(仅限可变集合)

>>> s
set([‘c‘, ‘e‘, ‘h‘, ‘o‘, ‘p‘, ‘s‘])
>>> s.add(‘z‘)
>>> s
set([‘c‘, ‘e‘, ‘h‘, ‘o‘, ‘p‘, ‘s‘, ‘z‘])
>>> s.update(‘pypi‘)
>>> s
set([‘c‘, ‘e‘, ‘i‘, ‘h‘, ‘o‘, ‘p‘, ‘s‘, ‘y‘, ‘z‘])
>>> s.remove(‘z‘)
>>> s
set([‘c‘, ‘e‘, ‘i‘, ‘h‘, ‘o‘, ‘p‘, ‘s‘, ‘y‘])
>>> s -= set(‘pypi‘)
>>> s
set([‘c‘, ‘e‘, ‘h‘, ‘o‘, ‘s‘])
>>> s -= set(‘cepp‘)  #如果不存在的元素也不会报错‘pp’
>>> s
set([‘h‘, ‘o‘, ‘s‘])
>>> t
frozenset([‘b‘, ‘h‘, ‘k‘, ‘o‘, ‘p‘, ‘s‘])
>>> t.add(‘z‘)          #不可变集合无法添加修改
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: ‘frozenset‘ object has no attribute ‘add‘

删除集合

>>> s
set([‘h‘, ‘o‘, ‘s‘])
>>> s.remove(‘o‘)
>>> t
frozenset([‘b‘, ‘h‘, ‘k‘, ‘o‘, ‘p‘, ‘s‘])
>>> t.remove(‘b‘)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: ‘frozenset‘ object has no attribute ‘remove‘
>>> del s
>>> s
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name ‘s‘ is not defined

(适用于可变和不可变集合的)集合类型操作符

集合等价/不等价

两个集合相等,对每一个集合而言,当且仅当其中一个集合中的每个成员同时也是另一个集合中的成员。这和集合成员的顺序无关,只和集合的元素有关。

>>> s = set(‘sleep‘)
>>> s
set([‘p‘, ‘s‘, ‘e‘, ‘l‘])
>>> t = set(‘plese‘)
>>> t
set([‘p‘, ‘s‘, ‘e‘, ‘l‘])
>>> o = frozenset(‘peles‘)
>>> o
frozenset([‘p‘, ‘s‘, ‘e‘, ‘l‘])
>>> s == t == o
True
子集/超集

集合支持严格子集(<)和非严格子集(<=),也支持严格(>)超集和非严格(>=)超集。

>>> set(‘shop‘) < set(‘cheeseshop‘)
True
>>> set(‘shop‘) <= set(‘cheeseshop‘)
True
>>> set(‘bookshop‘) >= set(‘shop‘)
联合(|)(union())

两个集合联合成一个新集合,该集合的每一个元素都至少是其中一个集合的成员。可以用于集合结合去重

>>> s = set(‘shop‘)
>>> t = set(‘bookshop‘)
>>> s | t
set([‘b‘, ‘h‘, ‘k‘, ‘o‘, ‘p‘, ‘s‘])
>>> s.union(t)
set([‘b‘, ‘h‘, ‘k‘, ‘o‘, ‘p‘, ‘s‘])
>>> o = frozenset(‘cheeseshop‘)
>>> o | s
frozenset([‘p‘, ‘c‘, ‘e‘, ‘h‘, ‘s‘, ‘o‘])
交集(&)(intersection())
>>> s
set([‘h‘, ‘s‘, ‘o‘, ‘p‘])
>>> t
set([‘b‘, ‘h‘, ‘k‘, ‘o‘, ‘p‘, ‘s‘])
>>> s & t
set([‘h‘, ‘s‘, ‘o‘, ‘p‘])
>>> s.intersection(t)
set([‘h‘, ‘s‘, ‘o‘, ‘p‘])
差集/相对补集(-) (difference())

(t-s)生产一个集合,该集合的元素,只属于集合t,不属于集合s

>>> s
set([‘h‘, ‘s‘, ‘o‘, ‘p‘])
>>> t
set([‘b‘, ‘h‘, ‘k‘, ‘o‘, ‘p‘, ‘s‘])
>>> t-s
set([‘k‘, ‘b‘])
>>> t.difference(s)
set([‘k‘, ‘b‘])
>>> 
对称差分(^)(symmetric_difference())

(t^s)生产一个集合,该集合,不能同时属于两个集合

>>> s
set([‘h‘, ‘s‘, ‘o‘, ‘p‘])
>>> t
set([‘b‘, ‘h‘, ‘k‘, ‘o‘, ‘p‘, ‘s‘])
>>> t ^ s
set([‘b‘, ‘k‘])
>>> t.symmetric_difference(s)
set([‘b‘, ‘k‘])
以上,如果t是一个不可变集合,那么s做为左操作数时和上面结果一致,如果t做为左操作数,结果就变成了不可变集合
>>> s
set([‘h‘, ‘s‘, ‘o‘, ‘p‘])
>>> t = frozenset(‘bookshop‘)
>>> t
frozenset([‘b‘, ‘h‘, ‘k‘, ‘o‘, ‘p‘, ‘s‘])
>>> t | s
frozenset([‘p‘, ‘s‘, ‘b‘, ‘h‘, ‘k‘, ‘o‘])
>>> t & s
frozenset([‘h‘, ‘s‘, ‘o‘, ‘p‘])
>>> t - s
frozenset([‘k‘, ‘b‘])
>>> t ^ s
frozenset([‘b‘, ‘k‘])

(仅适用于可变集合)集合类型操作符

|=:以存在集合添加成员
>>> s = set(‘cheeseshop‘)
>>> s
set([‘c‘, ‘e‘, ‘h‘, ‘o‘, ‘p‘, ‘s‘])
>>> s |= set(‘pypi‘)
>>> s
set([‘c‘, ‘e‘, ‘i‘, ‘h‘, ‘o‘, ‘p‘, ‘s‘, ‘y‘])
&=:保留与其他集合共有的成员
>>> s = set(‘cheeseshop‘)
>>> s
set([‘c‘, ‘e‘, ‘h‘, ‘o‘, ‘p‘, ‘s‘])
>>> s &= set(‘shop‘)
>>> s
set([‘h‘, ‘s‘, ‘o‘, ‘p‘])
-=:(s-=t)集合s去除集合t后剩下的元素
>>> s = set(‘cheeseshop‘)
>>> s
set([‘c‘, ‘e‘, ‘h‘, ‘o‘, ‘p‘, ‘s‘])
>>> s -= set(‘shop‘)
>>> s
set([‘c‘, ‘e‘])
^=:不能同时属于两个集合
>>> s = set(‘cheeseshop‘)
>>> s
set([‘c‘, ‘e‘, ‘h‘, ‘o‘, ‘p‘, ‘s‘])
>>> t = frozenset(‘bookshop‘)
>>> t
frozenset([‘b‘, ‘h‘, ‘k‘, ‘o‘, ‘p‘, ‘s‘])
>>> s ^= t
>>> s
set([‘c‘, ‘b‘, ‘e‘, ‘k‘])

其他的函数

s.issubset(t):如果s是t的子集,返回True,否则返回False
s.issuperset(t):如果s是t的超集,返回True,否则返回False
s.discard(obj):remove()的友好版本,如果s种存在obj,从s种删除它(适用于可变元素)

Python的字典和集合

标签:

原文地址:http://www.cnblogs.com/mrylong/p/5073912.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!