博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python set集合
阅读量:2455 次
发布时间:2019-05-10

本文共 7288 字,大约阅读时间需要 24 分钟。

说明:集合对象是一组无序排列的哈希的值,集合成员可以做字典中的键;

集合支持用in 和not in 操作符检查成员,由len()内建函数得到集合的大小,用for 循环迭代集合的成员,但是因为集合无序,所以不能通过创建索引或执行切片操作,也没有键可以用来获取集合中元素的值。除无序以外,集合内的元素不能重复

集合分为可变集合(set)和不可变集合(forzenset)。对于可变集合,可以用来添加和删除元素,但不可用来哈希,不能用来做字典的键,也不能做其他集合的元素。

不可变集合则相反,有哈希,可以添加删除,能被用来做字典的键和集合中的一员。

另外支持union(联合),intersection(交),difference(差),和sysmmetric difference(对称差集)等数学运算。

 

 

1:如何创建集合和给集合赋值:通过集合唯一的方法,set()和frozenset()

s = set('test')

print(s)
print(type(s))
print(len(s))
#### 输出结果
{
's', 't', 'e'}
<class 'set'>
3

 

2:如何访问集合中的值

s = set('thisistest')print('k' in s)print('t' in s)print('a' in s)for i in s:    print(i)#### 输出结果FalseTrueFalsehiets

 

 

集合方法:

1: set 类方法

class set(object):    """    set() -> new empty set object    set(iterable) -> new set object        Build an unordered collection of unique elements.    """

 

2:add --: 添加 元素集

def add(self, *args, **kwargs): # real signature unknown    """    .        .    """    pass

使用方法:

s = set('thisistest')print(s)s1 = s.add('zzzz')print(s)#### 输出结果{
't', 's', 'e', 'i', 'h'}{
'zzzz', 's', 't', 'e', 'i', 'h'}

 

3: clear-------清空

def clear(self, *args, **kwargs): # real signature unknown

    """ Remove allelements from this set. """
    pass

使用方法:

s = set('thisistest')

print(s)
print(s.clear())
#### 输出结果
{
'e', 't', 'i', 'h', 's'}
None

 

4: copy-------复制

def copy(self, *args, **kwargs): # real signature unknown

    """ Return a shallowcopy of a set. """
    pass

使用方法:

s = set('thisistest')s1 = s.copy()print("s:",s)print("s1:",s1)#### 输出结果s: {
't', 'h', 'i', 'e', 's'}s1: {
't', 'h', 'i', 'e', 's'}

 

5: difference ---- 对比set集合,返回值中没有的元素形成一个新的set集合

def difference(self, *args, **kwargs): # real signature unknown    """    Return the difference of two or more sets as a new set.        (i.e. all elements that are in this set but not the others.)    """    pass

使用方法:

s = set('thisistest')s1 = set('mynameistest')s2 = s.difference(s1)print(s.difference(s1))print(type(s2))#### 输出结果{
'h'}

 

6: difference_update --- 取差值元素,删除另一个集合中存在的元素

def difference_update(self, *args, **kwargs): # real signature unknown    """ Remove all elements of another set from this set. """    pass

使用方法:

s= set('thisistest')s1 = set('mynameistest')s2 = s.difference(s1)print(s.difference_update(s1))print(s)#### 输出结果None{
'h'}

 

7:discard --- 删除元素,如果存在元素,则删除

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

使用方法:

s = set('thisistest34')s1 = set('this')print("old:",s)s.discard('t')print("new:",s)#### 输出结果old: {
't', 'h', '3', 's', 'e', '4', 'i'}new: {
'h', '3', 's', 'e', '4', 'i'}

 

 

8:intersection --- 交集:返回两个集合的交集

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

使用方法:

s = set('thisistest34mymynameistest')s1 = set('mynameistest')s2 = s.intersection(s1)print(s)print(s2)print(s1)#### 输出结果{
't', 's', 'n', 'e', 'y', 'h', 'a', 'm', '3', 'i', '4'}{
't', 'n', 's', 'e', 'y', 'a', 'm', 'i'}{
't', 'n', 's', 'e', 'y', 'a', 'm', 'i'}

 

9:intersection_update 对比元素,只更新self,只保留和值中共同存在的元素

def intersection_update(self, *args, **kwargs): # real signature unknown    """ Update a set with the intersection of itself and another. """    pass

使用方法:

s= set('thisistest34')s1 = set('mynameistest')s.intersection_update(s1)print(s)print(s1)#### 输出结果{
't', 'e', 's', 'i'}{
'e', 's', 'n', 'm', 't', 'i', 'a', 'y'}

 

10: isdisjoint --- 如果有一个集合为空,则返回True

def isdisjoint(self, *args, **kwargs): # real signature unknown    """ Return True if two sets have a null intersection. """    pass

使用方法:

s = set('thisistest34')s1 = set('')print(s.isdisjoint(s1))#### 输出结果True

 

10:issubset ----  判断另一个集合是否包含,返回bool值

def issubset(self, *args, **kwargs): # real signature unknown    """ Report whether another set contains this set. """    pass

使用方法:

s = set('thisistest34')s1 = set('this')print(s.issubset(s1))print(s1.issubset(s))#### 输出结果FalseTrue

 

11:issuperset --- 判断自身是否包含另一个集合,返回bool值

def issuperset(self, *args, **kwargs): # real signature unknown    """ Report whether this set contains another set. """    pass

使用方法:

s = set('thisistest34')s1 = set('this')print(s.issuperset(s1))print(s1.issuperset(s))#### 输出结果TrueFalse

 

12:pop --- 删除任意元素并返回其值

def pop(self, *args, **kwargs): # real signature unknown    """    Remove and return an arbitrary set element.    Raises KeyError if the set is empty.    """    pass

使用方法:

s= set('thisistest34')s1 = set('this')print(s.pop())print(s)#### 输出结果3{
't', 'h', 'e', '4', 'i', 's'}### 再次执行s{
'i', 'h', 't', '4', 'e', '3'}

 

13: remove ---删除元素,如果元素不存在,将报错

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

使用方法:

s = set('thisistest34')s1 = set('this')s.remove('t')#print(s.pop())print(s)#### 输出结果{
'h', 'e', 'i', '4', '3', 's'}

 

14: symmetric_difference --- 返回两个集合的不同元素

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

使用方法:

s= set('thisistest34')s1 = set('this')s2 = s.symmetric_difference(s1)#print(s.pop())print(s2)#### 输出结果{
'3', 'e', '4'}

 

 

15:symmetric_difference_update– 更新自己为两个集合的不相等元素

def symmetric_difference_update(self, *args, **kwargs): # real signature unknown    """ Update a set with the symmetric difference of itself and another. """    pass

使用方法:

s= set('thisistest34')s1 = set('this')s.symmetric_difference_update(s1)#print(s.pop())print("s:",s)#### 输出结果s: {
'e', '3', '4'}

 

16: union --- 返回两个集合的并集生成一个新的集合

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

使用方法:

s = set('thisistest34')s1 = set('this56')print("s:",s)#print(s.pop())print(s1.union(s))#### 输出结果s: {
'h', '4', 't', 'i', 's', 'e', '3'}{
'6', '5', 'h', '4', 't', 'i', 's', 'e', '3'}

 

 

17:update -- : 添加多项至本身

def update(self, *args, **kwargs): # real signature unknown    """ Update a set with the union of itself and others. """    pass

使用方法:

s = set('thisistest34')s1 = set('this56')print("old:",s)s.update(s1)print("new:",s)#### 输出结果old: {
'i', '3', 'e', 'h', '4', 't', 's'}new: {
'i', '3', 'e', 'h', '4', 't', '5', 's', '6'}

 

小实验:寻找差异

# 数据库中原有

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 }}

需要删除:?

需要新建:?

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

 

操作方法:

old_set = set(old_dict.keys())

print(old_set)
update_list
= list(old_set.intersection(new_dict.keys()))
print("update_list:",update_list)
new_list
= []
del_list
= []
for i in new_dict.keys():
   
print("new_keys:",i)
   
if i not in update_list:
       
new_list.append(i)
for i in old_dict.keys():
   
print("old_dict_key:" ,i)
   
if i not in update_list:

 

转载地址:http://pedhb.baihongyu.com/

你可能感兴趣的文章
cloud-init_使用Cloud-init将节点添加到您的私有云
查看>>
ci/cd实践的必要性_8种CI / CD最佳实践,助您成功
查看>>
开源社区管理机制_如何管理蓬勃发展的公司主导的开源社区
查看>>
远程匿名聊天_爱还是恨聊天? 远程团队的4个最佳实践
查看>>
基于Elasticsearch和Kibana的COVID-19仪表板
查看>>
net开源开发web框架_自定义我的用于Web开发的开源PHP框架
查看>>
第三章承诺和一致_承诺问题:组织心理和公开管理的好处
查看>>
reveal.js下载教程_使用Reveal.js和Git创建网络教程
查看>>
cobol语言发展趋势_COBOL是您的计划B吗? 以及更多的行业趋势
查看>>
caldav选择导入日历_如何用安全的日历协议替换CalDAV
查看>>
三大开源社区是哪几个_3个衡量开源社区健康的指标
查看>>
chocolatey_开始使用开源Windows软件包管理器:Chocolatey
查看>>
c# 绘图 数据科学_使用C和C ++进行数据科学
查看>>
4名从事少数族裔科技职业的技术人员
查看>>
成熟度评估_如何评估组织的技术成熟度
查看>>
win10打印机共享来宾_检测来宾虚拟机中的CPU窃取时间
查看>>
政府软件变革 云原生_云原生软件的6个要求
查看>>
rust编程_C vs. Rust:用于编程硬件抽象的选择
查看>>
vue计算属性用于什么场景_什么是用于安全计算的HTTPS?
查看>>
2020徐涛核心考案_在2020年提升技术职业水平的4种核心技能
查看>>