#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/8/22 13:42
# @Author : limingyu
# @Site :
# @File : Test_set.py
# @Software: PyCharm
###################Set (无序,不重复序列 )#####################
#1、set:
#a.创建
tupl = () #元组
li = [] #列表
dic = {"li":123} #字典
se = {"123","345"} #set
print(type(tupl)) #<class 'tuple'>
print(type(li)) #<class 'list'>
print(type(dic)) #<class 'dict'>
print(type(se)) #<class 'set'>
#创建list两种方式,方式一只是一种规则,内部原理是调用方式二
li = [12,3,4] #方式一
# 方式二list(),自动调用构造方法__init__, __init__内部执行
#for循环将(1,2,3,4)转为[1,2,3,4]
list((1,2,3,4))
#创建set两种方式
s = {3,2} #方式一:规则
set() #方式二:方法,创建空集合
s1 = set([1,2,3,4]) #将列表转为集合set
#b. 功能:操作集合
s = set()
print(s) #set()
#b.1、添加元素
s.add(123)
s.add(123)
print(s) #{123}
#b.2、清空
s.clear()
print(s) #set()
#b.3、并交集
s1 = {11,22,33}
s2 = {22,33,44}
s3 = s1.difference(s2) #s1中存在s2中不存在
print(s3) #{11}
s4 = s1.symmetric_difference(s2) #s1与s2中不相同的值
print(s4) #{11, 44}
s1.difference_update(s2) #将新的结果更新到s1
print(s1) #{11}
#取交集
s1 = {11,22,33}
s2 = {22,33,44}
s3 = s1.intersection(s2)
print(s3) #{33, 22}
#取并集
s3 = s1.union(s2)
print(s3) #{33, 22, 11, 44}
#移除元素
s1 = {11,22,33}
s1.discard(11) #移除指定元素,不存在不报错,重要
print(s1) #{33, 22}
#s1.remove(1111) #移除指定元素,不存在即报错 ,KeyError: 1111
res = s1.pop() #随机移除元素,并返回
print(res) #33
#批量更新
s1 = {1,2,3}
li = [5,6,6]
s1.update(li) #元组,列表,字符串都可以批量更新
print(s1) #{1, 2, 3, 5, 6}
#自动调用方法
li = [11,22,3,4] #list __init__
li() #list __call__
li[0] #list __getitem__
li[0] = 123 #list __setitem__
del li[0] #list __delitem__
#集合实战
#需求:三个插槽1,2,4分别插入8,4,2G的内存条,现分别更新为1,2,3为4,4,2G内存
old_dict = {
"#1" : 8,
"#2" : 4,
"#4" : 2,
}
new_dict = {
"#1" : 4,
"#2" : 4,
"#4" : 2,
}
#取出字典中的key,转为set,用set的方法
#删除的槽位
new_set = set(new_dict.keys())
old_set = set(old_dict.keys())
remove_set = old_set.difference(new_set)
#增加的槽位
add_set = new_set.difference(old_set)
#更新的槽位
updte_set = old_set.intersection(new_set)
python基础之set
最新推荐文章于 2022-10-01 23:42:43 发布