首页 > 编程语言 > 详细

python学习第三天-集合

时间:2020-07-06 23:51:15      阅读:83      评论:0      收藏:0      [点我收藏+]

增:

  add

a = {1,2,3}
a.add(4)
print(a)
#{1, 2, 3, 4}

删:

  discard、remove、pop

a = {1,2,3}
a.remove(1)
print(a)
a.discard(1)
print(a)
a.discard(2)
print(a)
#{2, 3}
#{2, 3}
#{3}

改(不支持,也不支持切片,无索引):

a = {1,2,3}
print(a[0])
# File "E:/pythondir/Day01/task02.py", line 2, in <module>
    print(a[0])
TypeError: set object is not subscriptable

查:

  in or not in 

并集:

  | 、union

a = {1,2,3,4,5}
b = {2,3,5,6,7,8,9}
print(a | b)
print(a.union(b))
#{1, 2, 3, 4, 5, 6, 7, 8, 9}
#{1, 2, 3, 4, 5, 6, 7, 8, 9}

差集:

 -、difference 

a = {1,2,3,4,5}
b = {2,3,5,6,7,8,9}
print(a - b)
print(a.difference(b))
print(a.difference_update(b))  #去掉交集,并更新
print(a)
#{1, 4}
#{1, 4}
#None
#{1, 4}

交集:

  &、intersection

a = {1,2,3,4,5}
b = {2,3,5,6,7,8,9}
print(a & b)
print(a.intersection(b))
#{2, 3, 5}
#{2, 3, 5}

对称差集(两者并集去掉交集):

  ^、symmetric_difference

a = {1,2,3,4,5}
b = {2,3,5,6,7,8,9}
print(a ^ b)
print(a.symmetric_difference(b))
#{1, 4, 6, 7, 8, 9}
#{1, 4, 6, 7, 8, 9}

 

python学习第三天-集合

原文:https://www.cnblogs.com/thanos-ryan/p/13258136.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!