set集合

Posted yoyoua

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了set集合相关的知识,希望对你有一定的参考价值。

set

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

set具有的方法

1.add(self, *args, **kwargs)  添加

s = set([1,2,3,4,5])
s.add(6)
print(s)
{1, 2, 3, 4, 5, 6}

2.clear(self, *args, **kwargs)  清空

s = set([1,2,3,4,5])
s.clear()
print(s)

3.copy(self, *args, **kwargs)  拷贝

s = set([1,2,3,4,5])
a = s.copy()
print(a)
{1, 2, 3, 4, 5}

4.difference(self, *args, **kwargs)  

s = set([1,2,3,4,5,2])
print(s)
a = s.difference([1,2,])
print(a)
{1, 2, 3, 4, 5}
{3, 4, 5}

5.difference_update(self, *args, **kwargs)  删除当前set中的所有包含在 new set 里的元素

s = set([1,2,3,4,5,2])
a = s.difference_update([2])
print(s)
print(a)
{1, 3, 4, 5}
None

6.discard(self, *args, **kwargs)  移除元素

s = set([1,2,3,4,5,2])
s.discard(1)
print(s)

7.intersection(self, *args, **kwargs)  取交集,新创建一个set

s = set([1,2,3,4,5,2])
a = s.intersection([2,3,4])
print(a)
{2, 3, 4}

8.intersection_update(self, *args, **kwargs)  取交集,修改原来set

s = set([1,2,3,4,5,2])
s.intersection_update([2,3,4])
print(s)
{2, 3, 4}

9.isdisjoint(self, *args, **kwargs)  如果没有交集,返回true

s = set([1,2,3,4,5,2])
a = s.isdisjoint([6,7])
print(a)
True

10.issubset(self, *args, **kwargs)  是否是子集

s = set([1,2,3,4,5,])
a = s.issubset([1,2,3,4,5,6])
print(a)
True

11.issuperset(self, *args, **kwargs)  是否是父集

s = set([1,2,3,4,5,])
a = s.issuperset([1,2,3,])
print(a)
True

12. pop(self, *args, **kwargs)  移除

s = set([1,2,3,4,5,])
s.pop()
print(s)
{2, 3, 4, 5}

13.remove(self, *args, **kwargs)  移除

s = set([1,2,3,4,5,])
s.remove(3)
print(s)
{1, 2, 4, 5}

14.symmetric_difference(self, *args, **kwargs)  差集,创建新对象

s = set([1,2,3,4,5,])
a = s.symmetric_difference([1,2,3])
print(a)
{4, 5}

15.symmetric_difference_update(self, *args, **kwargs)  差集,改变原来

s = set([1,2,3,4,5,])
s.symmetric_difference_update([1,2,3])
print(s)

16.union(self, *args, **kwargs)  并集

s = set([1,2,3,4,5,])
a = s.union([1,2,3,6])
print(a)
{1, 2, 3, 4, 5, 6}

17.update(self, *args, **kwargs)  更新

s = set([1,2,3,4,5,])
s.update([1,2,7,8])
print(s)
{1, 2, 3, 4, 5, 7, 8}

 set实例

 1 #练习:寻找差异
 2 # 数据库中原有
 3 old_dict = {
 4     "#1":{ hostname:c1, cpu_count: 2, mem_capicity: 80 },
 5     "#2":{ hostname:c1, cpu_count: 2, mem_capicity: 80 },
 6     "#3":{ hostname:c1, cpu_count: 2, mem_capicity: 80 }
 7 }
 8 
 9 # cmdb 新汇报的数据
10 new_dict = {
11     "#1":{ hostname:c1, cpu_count: 2, mem_capicity: 800 },
12     "#3":{ hostname:c1, cpu_count: 2, mem_capicity: 80 },
13     "#4":{ hostname:c2, cpu_count: 2, mem_capicity: 80 }
14 }
15 old_set = set(old_dict.keys())
16 update_list = list(old_set.intersection(new_dict.keys()))
17 
18 new_list = []
19 del_list = []
20 
21 for i in new_dict.keys():
22     if i not in update_list:
23         new_list.append(i)
24 
25 for i in old_dict.keys():
26     if i not in update_list:
27         del_list.append(i)
28 
29 print(update_list,new_list,del_list)

 

以上是关于set集合的主要内容,如果未能解决你的问题,请参考以下文章

set集合关于set与set进行比较

集合类Set\Map

Python基础数据类型之set集合

java集合-Set集合

集合set

怎样从java集合类set中取出数据?