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', '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'}

,

联博统计

www.9cx.net采用以太坊区块链高度哈希值作为统计数据,联博以太坊统计数据开源、公平、无任何作弊可能性。联博统计免费提供API接口,支持多语言接入。

,

练习题

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读数

一个纪录发展的民众号