Python基础核心经典教程(020)——集合


版权声明

  • 本文原创作者:谷哥的小弟
  • 作者博客地址:http://blog.csdn.net/lfdfhl

概述

在Python中使用集合(set)存储信息,其特征如下:

  • 1、集合中的元素是无序的。
  • 2、集合中不能包含重复的元素。
  • 3、使用{ }或set( )创建集合。但是,如果要创建空集合只能使用set()。因为{ }用于创建空字典。
  • 4、集合支持 union(联合),intersection(交),difference(差)和 sysmmetric difference(对称差集)等数学运算。

示例

"""
原创作者:谷哥的小弟
博客地址:http://blog.csdn.net/lfdfhl
示例描述:集合
"""
# 创建空集合
s1 = set()
print(type(s1))

# 创建非空集合
s2 = {1, 2, 3, 4, 5}
print(s2)

# 创建非空集合
s3 = {1, 2, 3, 4, 5, 1, 2}
print(s3)

在这里插入图片描述

集合常用方法

在此,以示例形式详细介绍集合的常用方法。

与新增数据相关的方法

  • add( )添加单个数据
  • update( )添加序列数据

示例

"""
原创作者:谷哥的小弟
博客地址:http://blog.csdn.net/lfdfhl
示例描述:集合常用方法
"""

# 添加单个数据
s1 = {1, 2, 3, 4, 5}
s1.add(6)
s1.add(7)
print(s1)

# 添加序列数据
s2 = {1, 2, 3, 4, 5}
s2.update("tom")
print(s2)
s2.update([6, 7, 8])
print(s2)

在这里插入图片描述

与删除数据相关的方法

  • remove( )删除集合中的数据,如果该数据不存在则报错。
  • discard( )删除集合中的数据,如果该数据不存在也不会报错。
  • pop( )随机删除集合中的某个数据,并返回该数据。

示例

"""
原创作者:谷哥的小弟
博客地址:http://blog.csdn.net/lfdfhl
示例描述:集合常用方法
"""

# 利用remove从集合中删除数据
s1 = {1, 2, 3, 4, 5}
s1.remove(1)
print(s1)

# 利用discard从集合中删除数据
s2 = {1, 2, 3, 4, 5}
s2.discard(5)
print(s2)

# 利用pop从集合中删除数据
s3 = {"apple", "orange", "banana"}
result = s3.pop()
print(result)
print(s3)
result = s3.pop()
print(result)
print(s3)

在这里插入图片描述

与查找数据相关的方法

  • in 判断数据是否在集合中
  • not in判断数据是否不在集合中

示例

"""
原创作者:谷哥的小弟
博客地址:http://blog.csdn.net/lfdfhl
示例描述:集合常用方法
"""

# 利用in判断数据是否在集合中
s1 = {1, 2, 3, 4, 5}
result = 2 in s1
print(result)

# 利用not in判断数据是否不在集合中
s2 = {1, 2, 3, 4, 5}
result = 2 not in s2
print(result)

在这里插入图片描述

集合与数学运算

在此,以示例形式详细介绍集合与数学运算。

示例

"""
原创作者:谷哥的小弟
博客地址:http://blog.csdn.net/lfdfhl
示例描述:集合与数学运算
"""
a = {'a', 'b', 'c', 'd', 'r'}
b = {'a', 'c', 'l', 'm', 'z'}
# letters in a but not in b
result = a - b
print(result)
# letters in either a or b
result = a | b
print(result)
# letters in both a and b
result = a & b
print(result)
# letters in a or b but not both
result = a ^ b
print(result)

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

谷哥的小弟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值