小言_互联网的博客

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

331人阅读  评论(0)

版权声明

  • 本文原创作者:谷哥的小弟
  • 作者博客地址: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)


转载:https://blog.csdn.net/lfdfhl/article/details/105940281
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场