一、集合介绍
在python中集合看起来像是只有key的字典
在python解释器中表现为set
集合中的元素不允许重复
二、集合的创建和转换
创建
In [4]: s1 = set()
In [5]: s1
Out[5]: set() # 空的集合
In [6]: type(s1)
Out[6]: set
转换
In [9]: set('hello word')
Out[9]: {' ', 'd', 'e', 'h', 'l', 'o', 'r', 'w'}
In [10]: set( [ 'hello','word'] )
Out[10]: {'hello', 'word'}
In [12]: set( ( 'hello','word' ) )
Out[12]: {'hello', 'word'}
In [13]: set( { 'name':'shichen','age':'18' } )
Out[13]: {'age', 'name'}
三、集合运算
1. & 交集
获取两个集合都有的元素
In [14]: set1 = { 'hello','word' }
In [15]: set2 = { 'nihao','word' }
In [16]: set1 & set2
Out[16]: {'word'}
2. | 并集
把两个集合的元素并在一起
In [17]: set1 | set2
Out[17]: {'hello', 'nihao', 'word'}
3. - 差集
返回第一个元素中独有的元素
In [18]: set1 - set2
Out[18]: {'hello'}
In [19]: set2 - set1
Out[19]: {'nihao'}
4. ^ 异或交集
取两个集合分别独有的元素,组合为一个新的集合对象
In [20]: set1 ^ set2
Out[20]: {'hello', 'nihao'}
大型数据结构应用场景
In [30]: host_info=[]
In [31]: host_info.append({'192.168.1.11':{'cpu':['Intel(R) Core(TM) i5-5350U CPU @ 1.80GHz',4,1],'memory':['16','4','2'],'disk':['1T','2T']}})
In [32]: host_info.append({'192.168.1.12':{'cpu':['Intel(R) Core(TM) i5-5350U CPU @ 1.80GHz' ,4,1],'memory':['16','4','2'],'disk':['1T','2T']}})
In [33]: host_info
Out[33]:
[{'192.168.1.11': {'cpu': ['Intel(R) Core(TM) i5-5350U CPU @ 1.80GHz', 4, 1],
'memory': ['16', '4', '2'],
'disk': ['1T', '2T']}},
{'192.168.1.12': {'cpu': ['Intel(R) Core(TM) i5-5350U CPU @ 1.80GHz', 4, 1],
'memory': ['16', '4', '2'],
'disk': ['1T', '2T']}}]
取到 '192.168.1.11' 中的 ' 1T '
In [39]: host_info[0]
Out[39]:
{'192.168.1.11': {'cpu': ['Intel(R) Core(TM) i5-5350U CPU @ 1.80GHz', 4, 1],
'memory': ['16', '4', '2'],
'disk': ['1T', '2T']}}
In [42]: host_info[0].get('192.168.1.11').get('disk')[0]
Out[42]: '1T'