微信公众号:《Python读钱》有任何问题或建议,欢迎公众号Python中的消息集和数学集是一个概念。基本功能包括关系测试和消除重复元素。也可以对集合执行数学交集、并集和差集运算。定义集合的方式,见如下代码:①使用set()函数在[18]中:color_set=set(['green','blue','red','yellow','blue'])在[20]:color_setOut[20]:{'blue','green','red','yellow'}②使用{}定义,需要注意的是{}必须包含元素,empty{}定义为空字典In[19]:color_set={'green','blue','red','yellow','blue'}In[20]:color_setOut[20]:{'blue','green','red'','yellow'}可以看到set()会帮你去掉重复的元素(上面的'blue'),下面说说set的常用操作判断一个元素是否写在set中:elementinsetIn[21]:'blue'incolor_setOut[21]:TrueIn[22]:'white'incolor_setOut[22]:False添加元素到集合:set.add(element)In[23]:color_set.add('white')In[24]:color_setOut[24]:{'blue','green','red','white','yellow'}#如果你在集合中添加一个现有元素#它会被自动去重In[25]:color_set.add('blue')在[26]:color_setOut[26]:{'blue','green','red','white','yellow'}移除元素写法:set.remove(element)In[27]:color_set.remove('white')In[28]:color_setOut[28]:{'blue','green','red','yellow'}取集合的并集并写成:set_1.union(set_2)In[29]:color_set1=set(['格雷en','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','yellow'}取集合的交集: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的差集: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_set1中color_set2包含的元素In[34]:color_set2.difference(color_set1)Out[34]:{'black','pink','purple'}练习:给定两个列表,分别为[1,2,3,3,4,4,5]and[1,1,3,5,5,7,9],请根据这两个列表生成集合A和B,将元素5和7添加到集合A中,将元素添加到集合B中添加元素6和9求集合A和集合B的并集求集合A和集合B的交集求集合A-B的交集B-A扫码关注“Python读财经”,第一时间获取干货!
