码迷,mamicode.com
首页 > 其他好文 > 详细

Day11 集合、集合操作

时间:2018-04-18 23:36:22      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:基本操作   添加   存在   discard   int   长度   交集   col   nio   

  • 集合操作
  1. 去重:把一个列表变成集合,就自动去重了
  2. 关系测试:测试两组数据之前的交集、差集、并集等关系

集合:无序

list_1=[1,4,5,7,3,6,7,9]
#字符串->集合
list_1=set(list_1)
list_2=set([2,6,0,66,22,8,4])

#去重
print(list_1,type(list_1))
>>>{1, 3, 4, 5, 6, 7, 9} <class set>
print(list_1,list_2)
>>>{1, 3, 4, 5, 6, 7, 9} {0, 2, 66, 4, 6, 8, 22}

#交集
print(list_1.intersection(list_2))
>>>{4, 6}
print(list_1 & list_2)
>>>{4, 6}
#并集
print(list_1.union(list_2))
>>>{0, 1, 2, 3, 4, 5, 6, 7, 66, 9, 8, 22}

print(list_1 | list_2)
>>>{0, 1, 2, 3, 4, 5, 6, 7, 66, 9, 8, 22}

#差集 (in list_1 not in list_2)
print(list_1.difference(list_2))
>>>{1, 3, 5, 7, 9}
print(list_1 -list_2)
>>>{1, 3, 5, 7, 9}
#子集
list_3=set([1,3,7])
print(list_1.issubset(list_2))
>>>False
print(list_3.issubset(list_1))
>>>True
print(list_1.issubset(list_3))
>>>False

#父集
print(list_1.issuperset(list_3))
>>>True

#对称差集
print(list_1.symmetric_difference(list_2))
>>>{0, 1, 2, 66, 3, 5, 7, 8, 9, 22}
print(list_1 ^ list_2)
>>>{0, 1, 2, 66, 3, 5, 7, 8, 9, 22}
#如果有两个集合有一个空交集,返回True
list_4=set([5,6,8])
print(list_3.isdisjoint(list_3))
>>>False

 

  •  基本操作
#添加
print(list_1)
>>>{1, 3, 4, 5, 6, 7, 9}
list_1.add(666)
print(list_1)
>
>>{1, 3, 4, 5, 6, 7, 9, 666}
#添加多项
print(list_1)
>>>{1, 3, 4, 5, 6, 7, 9, 666} list_1.update([
111,222,333]) print(list_1)
>>>{1, 3, 4, 5, 6, 7, 9, 333, 111, 666, 222}
#删除 list_1.remove(111) print(list_1)
>>>{1, 3, 4, 5, 6, 7, 9, 333, 666, 222}
#删除,如果成员不存在,不会报错 print(list_1.discard(888))
>>>None
#长度 print(len(list_1))
>>>10
#测试集合存在某成员 print(222 in list_1)
>>>True
print(111 in list_1)
>>>False

 

Day11 集合、集合操作

标签:基本操作   添加   存在   discard   int   长度   交集   col   nio   

原文地址:https://www.cnblogs.com/q1ang/p/8877861.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!