您的位置:首页 > 编程语言 > Python开发

Python小白零基础入门 —— 集合(set)

2020-08-30 15:03 1391 查看

Python小白零基础入门 —— 集合(set)

点击上方“Python读数”,选择“星标”公众号
重磅干货,第一时间送达
Python零基础入门的第四篇文章,为大家介绍Python中集合的这一数据类型,读完这篇文章后,也就基本掌握了Python的基本数据类型。

Python中的集合和数学上的集合是一个概念,基本功能包括关系测试和消除重复元素,对于集合还可以进行数学上的交、并、差运算。定义一个集合的方式,见下面的代码:

①使用set()函数

In [18]: color_set = set(['green','blue','red','yellow','blue'])

In [20]: color_set
Out[20]: {'blue', 'green', 'red', 'yellow'}

②使用{}定义,需要注意的是{}必须含有元素,空的{}定义的是空的字典

In [19]: color_set = {'green','blue','red','yellow','blue'}

In [20]: color_set
Out[20]: {'blue', 'green', 'red', 'yellow'}

可以看到,set()会帮你去掉重复的元素(上方的'blue'),下面讲一下集合的常见操作

判断一个元素是否在集合内

写法:element in set

n [21]: 'blue' in color_set
Out[21]: True

In [22]: 'white' in color_set
Out[22]: False

往集合中添加元素

写法:set.add(element)

In [23]: color_set.add('white')

In [24]: color_set
Out[24]: {'blue', 'green', 'red', 'white', 'yellow'}

# 若添加集合中已有的元素
# 则会自动去重
In [25]: color_set.add('blue')

In [26]: color_set
Out[26]: {'blue', 'green', 'red', 'white', 'yellow'}

移除元素

写法:set.remove(element)

In [27]: color_set.remove('white')
#
# In [28]: color_set
# Out[28]: {'blue', 'green', 'red', 'yellow'}

取集合的并集

写法:set_1.union(set_2)

In [29]: color_set1 = set(['green','blue','red','yellow','blue'])

In [30]: color_set2 = set(['purple','blue','pink','black'])

In [31]: color_set1.union(color_set2)
Out[31]: {'black', 'blue', 'green', 'pink', 'red', '
38f8
purple', 'yell
ow'}

取集合的交集

写法:set_1.intersection(set_2)

In [29]: color_set1 = set(['green','blue','red','yellow','blue'])

In [30]: color_set2 = set(['purple','blue','pink','black'])

In [32]: color_set1.intersection(color_set2)
Out[32]: {'blue'}

取集合的差集

写法:set_1.difference(set_2)

In [29]: color_set1 = set(['green','blue','red','yellow','blue'])

In [30]: color_set2 = set(['purple','blue','pink','black'])

# ①在color_set1中去掉color_set2含有的元素
In [33]: color_set1.difference(color_set2)
Out[33]: {'green', 'red', 'yellow'}

# ②在color_set2中去掉color_set1含有的元素
In [34]: color_set2.difference(color_set1)
Out[34]: {'black', 'pink', 'purple'}

练习题

1,给定两个列表,分别为[1, 2, 3, 3, 4, 4, 5]和[1, 1, 3, 5, 5, 7, 9],请根据这两个列表分别生成集合A和B

2,往集合A中加入元素5和7,往集合B中加入元素6和9

3,求集合A和集合B的并集

4,求集合A和集合B的交集

5,求A-B和B-A

往期精彩回顾

Python小白零基础入门 —— 变量及简单的数据类型

Python小白零基础入门 —— 列表和元组

Python小白零基础入门 —— 字典

关注我们

1529321439513643.jpg
公众号:Python读数

一个记录成长的公众号

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐