python基础之set

#!/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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值