python小白练习简单代码_Python小白零基础入门 —— 集合(set)

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

练习题

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

一个记录成长的公众号

标签:blue,set,入门,Python,color,green,集合,red

来源: https://blog.51cto.com/14915204/2525874

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值