一、集合的定义

set集合,是一个无序且不重复的元素集合。

集合对象是一组无序排列的可哈希的值,集合成员可以做字典中的键。集合支持用in和not in操作符检查成员,由len()内建函数得到集合的基数(大小), 用 for 循环迭代集合的成员。但是因为集合本身是无序的,不可以为集合创建索引或执行切片(slice)操作,也没有键(keys)可用来获取集合中元素的值。

二、集合的创建

s = set()
s = {11,22,33,44} *注:创建空集合时,只能用set(),如果用第二种方法s={},创建的实际上是一个空字典。
s = {}
print(type(s))
<class 'dict'>
a=set('boy')
b=set(['y', 'b', 'o','o'])
c=set({"k1":'v1','k2':'v2'})
d={'k1','k2','k2'}
e={('k1', 'k2','k2')}
print(a,type(a))
print(b,type(b))
print(c,type(c))
print(d,type(d))
print(e,type(e))
执行结果如下:
{'o', 'b', 'y'} <class 'set'>
{'o', 'b', 'y'} <class 'set'>
{'k1', 'k2'} <class 'set'>
{'k1', 'k2'} <class 'set'>
{('k1', 'k2', 'k2')} <class 'set'>

三、集合的功能

class set(object):
"""
set() -> new empty set object
set(iterable) -> new set object Build an unordered collection of unique elements.
"""
def add(self, *args, **kwargs): # real signature unknown
"""
Add an element to a set,添加元素 This has no effect if the element is already present.
"""
pass def clear(self, *args, **kwargs): # real signature unknown
""" Remove all elements from this set. 清楚内容"""
pass def copy(self, *args, **kwargs): # real signature unknown
""" Return a shallow copy of a set. 浅拷贝 """
pass def difference(self, *args, **kwargs): # real signature unknown
"""
Return the difference of two or more sets as a new set. A中存在,B中不存在 (i.e. all elements that are in this set but not the others.)
"""
pass def difference_update(self, *args, **kwargs): # real signature unknown
""" Remove all elements of another set from this set. 从当前集合中删除和B中相同的元素"""
pass def discard(self, *args, **kwargs): # real signature unknown
"""
Remove an element from a set if it is a member. If the element is not a member, do nothing. 移除指定元素,不存在不保错
"""
pass def intersection(self, *args, **kwargs): # real signature unknown
"""
Return the intersection of two sets as a new set. 交集 (i.e. all elements that are in both sets.)
"""
pass def intersection_update(self, *args, **kwargs): # real signature unknown
""" Update a set with the intersection of itself and another. 取交集并更更新到A中 """
pass def isdisjoint(self, *args, **kwargs): # real signature unknown
""" Return True if two sets have a null intersection. 如果没有交集,返回True,否则返回False"""
pass def issubset(self, *args, **kwargs): # real signature unknown
""" Report whether another set contains this set. 是否是子序列"""
pass def issuperset(self, *args, **kwargs): # real signature unknown
""" Report whether this set contains another set. 是否是父序列"""
pass def pop(self, *args, **kwargs): # real signature unknown
"""
Remove and return an arbitrary set element.
Raises KeyError if the set is empty. 移除元素
"""
pass def remove(self, *args, **kwargs): # real signature unknown
"""
Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. 移除指定元素,不存在保错
"""
pass def symmetric_difference(self, *args, **kwargs): # real signature unknown
"""
Return the symmetric difference of two sets as a new set. 对称交集 (i.e. all elements that are in exactly one of the sets.)
"""
pass def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
""" Update a set with the symmetric difference of itself and another. 对称交集,并更新到a中 """
pass def union(self, *args, **kwargs): # real signature unknown
"""
Return the union of sets as a new set. 并集 (i.e. all elements that are in either set.)
"""
pass def update(self, *args, **kwargs): # real signature unknown
""" Update a set with the union of itself and others. 更新 """
pass

源码

基本功能:

  • 增加
a=set('python')
a.add('tina')
print(a)
b=set('python')
b.update('tina')
print(b)
执行结果如下:
{'tina', 'o', 'p', 'n', 't', 'y', 'h'}
{'o', 'i', 'p', 'a', 'n', 't', 'y', 'h'}
##################
由以上代码可以看出,add是单个元素的添加,而update是批量的添加。输出结果是无序的,并非添加到尾部。
  • 删除(remove,discard,pop)
c={'p', 'i', 'h', 'n', 'o', 'y', 't'}
c.remove('p')
print(c)
c={'p', 'i', 'h', 'n', 'o', 'y', 't'}
c.discard('p')
print(c)
c={'p', 'i', 'h', 'n', 'o', 'y', 't'}
c.pop()
print(c)
执行结果如下: {'i', 'h', 't', 'o', 'y', 'n'} 
#####
当执行c.remove('p','i')和c.discard('p','i')时,报错:TypeError: remove() takes exactly one argument (2 given),说明remove和discard删除元素时都只能一个一个的删,同add对应。
#################################################################################
remove,pop和discard的区别:
discard删除指定元素,当指定元素不存在时,不报错;
remove删除指定元素,但当指定元素不存在时,报错:KeyError。
pop删除任意元素,并可将移除的元素赋值给一个变量,不能指定元素移除。
  • 清空
c={'p', 'i', 'h', 'n', 'o', 'y', 't'}
c.clear()
print(c)
执行结果如下:
set()

set的特有功能:

s1 = {0}
s2 = {i % 2 for i in range(10)}
s = set('hi')
t = set(['h', 'e', 'l', 'l', 'o'])
print(s.intersection(t), s & t) # 交集
print(s.union(t), s | t) # 并集
print(s.difference(t), s - t) # 差集
print(s.symmetric_difference(t), s ^ t) # 对称差集
print(s1.issubset(s2), s1 <= s2) # 子集(被包含)
print(s1.issuperset(s2), s1 >= s2) # 父集(包含) 执行结果如下:
{'h'} {'h'}
{'i', 'e', 'h', 'l', 'o'} {'i', 'e', 'h', 'l', 'o'}
{'i'} {'i'}
{'e', 'l', 'o', 'i'} {'e', 'l', 'o', 'i'}
True True
False False
s = {11,22,33}
t = {22,44}
print(s.isdisjoint(t))#(disjoint脱节的,)即如果没有交集,返回True,否则返回False
s.difference_update(t)#将差集覆盖到源集合,即从当前集合中删除和B中相同的元素
print(s)
执行结果如下:
False
{33, 11} s = {11,22,33}
t = {22,44}
s.intersection_update(t)#将交集覆盖到源集合
print(s)
执行结果如下:
{22} s = {11,22,33}
t = {22,44}
s.symmetric_difference_update(t)#将对称差集覆盖到源集合
print(s)
执行结果如下:
{33, 11, 44}

四、集合的转换

se = set(range(4))
li = list(se)
tu = tuple(se)
st = str(se)
print(li,type(li))
print(tu,type(tu))
print(st,type(st))
执行结果如下:
[0, 1, 2, 3] <class 'list'>
(0, 1, 2, 3) <class 'tuple'>
{0, 1, 2, 3} <class 'str'>

五、练习题

寻找差异:哪些需要删除?哪些需要新建?哪些需要更新?

# 数据库中原有
old_dict = {
"#1":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 },
"#2":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 }
"#3":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 }
} # cmdb 新汇报的数据
new_dict = {
"#1":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 800 },
"#3":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 }
"#4":{ 'hostname':c2, 'cpu_count': 2, 'mem_capicity': 80 }
} 

注意:无需考虑内部元素是否改变,只要原来存在,新汇报也存在,就是需要更新

del_dict = set(old_dict).difference(set(new_dict))
add_dict = set(new_dict).difference(set(old_dict))
update_dict = set(new_dict).intersection(set(old_dict))
print(del_dict)
print(add_dict)
print(update_dict)
执行结果如下:
{'#2'}
{'#4'}
{'#3', '#1'}
#!/usr/bin/python
# -*- coding:utf-8 -*-
old_dict = {
"#1": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80},
"#2": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80},
"#3": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80},
} new_dict = {
"#1": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 800},
"#3": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80},
"#4": {'hostname': 'c2', 'cpu_count': 2, 'mem_capicity': 80},
}
new_set = set()
old_set = set()
for i in new_dict:
new_set.add(i)
for j in old_dict:
old_set.add(j)
new_add = new_set.difference(old_set) #new_dict中有,old_dict中沒有
old_del = old_set.difference(new_set) #old_dict中有,new_dict中沒有
update = new_set.intersection(old_set) #old_dict和new_dict共同有的,需要把new_dict更新到old_dict中 for k in new_add:
old_dict[k] = new_dict[k] #將new_dict中新增的內容添加到old_dict中
for v in old_del:
del old_dict[v] #將old_dict中失效的內容刪除
for m in update:
old_dict[m] = new_dict[m] #把new_dict更新到old_dict中 print(old_dict)

python基本数据类型之集合set的更多相关文章

  1. python基本数据类型之集合

    python基本数据类型之集合 集合是一种容器,用来存放不同元素. 集合有3大特点: 集合的元素必须是不可变类型(字符串.数字.元组): 集合中的元素不能重复: 集合是无序的. 在集合中直接存入lis ...

  2. Python基础数据类型之集合

    Python基础数据类型之集合 集合(set)是Python基本数据类型之一,它具有天生的去重能力,即集合中的元素不能重复.集合也是无序的,且集合中的元素必须是不可变类型. 一.如何创建一个集合 #1 ...

  3. Python基础数据类型之集合以及其他和深浅copy

    一.基础数据类型汇总补充 list  在循环一个列表时,最好不要删除列表中的元素,这样会使索引发生改变,从而报错(可以从后向前循环删除,这样不会改变未删元素的索引). 错误示范: lis = [,,, ...

  4. Python开发——数据类型【集合】

    集合的定义 由一个或多个确定的元素所构成的整体 可变集合 s=set('hello') print(s) # {'e', 'l', 'o', 'h'} s=set(['alex','alex','Lu ...

  5. Python - 基础数据类型 set 集合

    集合的简介 集合是一个无序.不重复的序列 它的基本用法包括成员检测和消除重复元素 集合对象也支持像 联合,交集,差集,对称差分等数学运算 集合中所有的元素放在 {} 中间,并用逗号分开 集合的栗子 这 ...

  6. python【数据类型:集合】

  7. python之数据类型补充、集合、深浅copy

    一.内容回顾 代码块: 一个函数,一个模块,一个类,一个文件,交互模式下,每一行就是一个代码块. is == id id()查询对象的内存地址 == 比较的是两边的数值. is 比较的是两边的内存地址 ...

  8. python 标准类库-数据类型之集合-容器数据类型

    标准类库-数据类型之集合-容器数据类型   by:授客 QQ:1033553122 Counter对象 例子 >>> from collections import Counter ...

  9. Python基础数据类型-列表(list)和元组(tuple)和集合(set)

    Python基础数据类型-列表(list)和元组(tuple)和集合(set) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 本篇博客使用的是Python3.6版本,以及以后分享的 ...

随机推荐

  1. Thinkphp中自己组合的数据怎样使用框架的分页

    做项目有时候,需要自己处理组合数据,不是直接从表中提取出来的.不能按照手册得方法分页显示数据.这时候就得想办法,正好看到他人的方法.地址为:http://www.thinkphp.cn/code/27 ...

  2. artdialog4.1.7 中父页面给子页面传值

    artdialog4.1.7中父页面给子页面传值时看了一些网友的解决方法: 在父页面声明全局变量 var returnValue=“ ”,子页面用art.dialog.opener.returnVal ...

  3. 常用js或jq效果汇总

    实时监控输入框改变    $('#password').bind('input propertychange', function() {}

  4. js 查找关键字

    查找:4种: 1. 查找固定关键字,仅返回位置,可指定开始位置: var i=str.indexOf("kword"[,starti]); str.lastIndexOf(&quo ...

  5. 友盟推送里面的Alias怎么用?可以理解成账号吗?

    友盟推送里面的Alias怎么用?可以理解成账号吗? 我们的App有自己的账号体系的,想在每次用户登陆的时候,给用户发一个欢迎消息. 看了一下友盟推送,里面有一个概念叫做Alias(别名),但是官方文档 ...

  6. 10/12 study

    [患者版]加号选择页: 这是四个TableView放在Scrollview上 上面是个xib封装的view 整体就是个scrollView,用xib摆上去的控件:   上面加了黄条,旧的控件统一修改y ...

  7. JavaScript 代码 优化笔记

    1. 判断某个元素是否在数组中. setCheckNodes : function (zNodes, checkIds){ var that = this; that.setAllNodesUnche ...

  8. ExtJs 使用点滴 十四 通过设置CheckboxSelectionModel属性值来实现GridPanel复选框可用不可用

    var sm = new Ext.grid.CheckboxSelectionModel({singleSelect : false,renderer:function(v, p, record)   ...

  9. nginx yii2环境配置

    #user nobody;worker_processes 2;#worker_cpu_affinity 0001 0010 0100 1000 #error_log logs/error.log;# ...

  10. SVN 多项目管理(强烈建议每个项目建一个库)

    Subversion的目录结构是很自由的,所有的规划都必须是你自己规定,考虑一个 subversion仓库的目录树,你可以把任何一个目录认定为一个项目,你可以只checkout这个目录下的所有文件进行 ...