码迷,mamicode.com
首页 > 编程语言 > 详细

Python基础操作-集合

时间:2017-07-26 17:34:06      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:ror   error   mod   交集   discard   span   数据类型   ace   方法   

Python set是基本数据类型的一种集合类型,它有可变集合(set())和不可变集合(frozenset)两种。创建集合set集合set添加集合删除交集并集差集的操作都是非常实用的方法。

list_1 = set([1,3,5,7,5,8,10])

list_2 = set([2,3,4,5,6,7,8])

list_3 = set([1,3,5])

一:基本操作

添加一个add

list_1.add(123)
print(list_1)
{1, 3, 5, 7, 8, 10, 123}

添加多个update

list_1.update([10,20,30,50])
print(list_1)
{1, 3, 5, 7, 8, 10, 50, 20 , 30}

删除remove 如果删除列表内没有的则会报错

list_1.remove(1)
print(list_1)
{3, 5, 7, 8, 10}

list_1.remove(20)
print(list_1)


Traceback (most recent call last):
  File "D:/PyCharm/day1/集合测试.py", line 14, in <module>
    list_1.remove(20)
KeyError: 20

删除discard 如果删除列表内没有的不会报错

list_1.discard(20)
print(list_1)
{1, 3, 5, 7, 8, 10}

删除pop 随机删除一个成员

list_1.pop()
print(list_1)
{3, 5, 7, 8, 10}

二:关系测试

交集

print(list_1.intersection(list_2))

{8, 3, 5, 7}

并集

print(list_1.union(list_2))

{1, 2, 3, 4, 5, 6, 7, 8, 10}

差集

print(list_1.difference(list_2))

{1, 10}

子集

print(list_3.issubset(list_1))

True

父集

print(list_1.issuperset(list_3))

True

对称差集

print(list_1.symmetric_difference(list_2))

{1, 2, 4, 6, 10}

 

Python基础操作-集合

标签:ror   error   mod   交集   discard   span   数据类型   ace   方法   

原文地址:http://www.cnblogs.com/manger/p/7240130.html

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