首页 > 代码库 > python函数

python函数

set 添加一个无序的,用set方法,访问速度快,天生解决了重复问题

1、difference 指定某个元素从原来set取出,并生成新的set

1 #difference
2 a = set(["aaa","bbb","ccc","aaa"])
3 print(a)
4 b = a.difference(["aaa"])
5 print(b)
6 
7 {ccc, bbb, aaa}
8 {ccc, bbb}

 

2、difference_update 删除原来set里某个元素

 1 #difference_update
 2 a = set(["aaa","bbb","ccc","aaa"])
 3 print(a)
 4 b = a.difference_update(["aaa"])
 5 print(a)
 6 print(b)
 7 
 8 
 9 {bbb, ccc, aaa}
10 {bbb, ccc}
11 None

 

 

3、pop 删除某个元素

 1 #pop
 2 a = set(["aaa","bbb","ccc","aaa"])
 3 print(a)
 4 b = a.pop()
 5 print(a)
 6 print(b)
 7 
 8 
 9 {aaa, bbb, ccc}
10 {bbb, ccc}
11 aaa

 

 

4、remove 删除指定元素

 1 #remove
 2 a = set(["aaa","bbb","ccc","aaa"])
 3 print(a)
 4 b = a.remove("ccc")
 5 print(a)
 6 print(b)
 7 
 8 
 9 {bbb, ccc, aaa}
10 {bbb, aaa}
11 None

 

 

这里举一个例子,更新、删除、添加原来的表

 1 old_dict = {
 2     "#1": {hostname: c1, cpu_count: 2, mem_capicity: 80},
 3     "#2": {hostname: c1, cpu_count: 2, mem_capicity: 80},
 4     "#3": {hostname: c1, cpu_count: 2, mem_capicity: 80}
 5 }
 6 # cmdb 新汇报的数据
 7 new_dict = {
 8     "#1": {hostname: c1, cpu_count: 2, mem_capicity: 800},
 9     "#3": {hostname: c1, cpu_count: 2, mem_capicity: 80},
10     "#4": {hostname: c2, cpu_count: 2, mem_capicity: 80}
11 }
12 
13 a = set(old_dict.keys())
14 b = set(new_dict.keys())
15 
16 #要更新的数据
17 update_set = a.intersection(b)
18 print(update_set)
19 #要删除的数据
20 delete_set = a.symmetric_difference(update_set)
21 print(delete_set)
22 #要添加的数据
23 add_set = b.symmetric_difference(update_set)
24 print(add_set)
25 
26 
27 
28 {#3, #1}
29 {#2}
30 {#4}

 

python函数