集合

set

特点:天生去重,无序,没有下标

l = [1,1,2,2,3,3,4,4,5,5]
l2 = {1,2,3,4,5,5,6,8}#集合的定义也用大括号,但是自动去重
s = set(l)
print(s)
print(l2)

输出结果:
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 6, 8}
  1. 定义空集合:
l2 = set()

交集,并集,差集

新增元素
l3 = set()
l3.add(8) #新增元素
删除元素
l2 = {1,2,5,6,8}
l2.remove(8)#删除元素
把一个集合加入到另一个集合里
l = [1,1,2,2,3,3,4,4,5,5]
l2 = {1,2,5,6,8}
l2.update(l)
交集(常用):intersection方法,&方法
stu1 = ['fd','wxl','zjr','lhy']
stu2 = ['fd','wxl','dsx','cc']
stu1_set = set(stu1)#list转换为集合
stu2_set = set(stu2)#list转换为集合
print(stu1_set.intersection(stu2_set))#取交集
print(stu1_set&stu2_set)#取交集
#例子

import string

password = 'abc123A'

password_set = set(password)

if password_set & set(string.digits) and password_set & set(string.ascii_lowercase) \
    and password_set & set(string.ascii_uppercase):
    print('密码合法')
else:
    print('不合法')
并集(常用):union方法,|方法
s1 = {1,2,3,4}
s2 = {4,5,6,7}
print(s1.union(s2))
print(s1 | s2)
差集(用得少):在一个集合里存在,在另一个集合不存在
s1 = {1,2,3,4}
s2 = {4,5,6,7}
print(s1.difference(s2))#在s1集合里存在,在s2集合不存在
print(s1-s2)

输出结果:
{1, 2, 3}
{1, 2, 3}
对称差集(用的少):去除在多个集合里同事存在的元素
s1 = {1,2,3,4}
s2 = {4,5,6,7}
print(s1^s2)
print(s1.symmetric_difference(s2))

输出结果:
{1, 2, 3, 5, 6, 7}
{1, 2, 3, 5, 6, 7}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值