首页 > 其他 > 详细

Pyython学习之set集合

时间:2018-09-22 00:40:28      阅读:221      评论:0      收藏:0      [点我收藏+]

set集合以{}保存一组可迭代对象,如列表,字符串,set集合本身。集合内的元素若有重复的,将自动去除重复元素

1 a=set([1,2,3])
2 print(a)
3 b=set(hello python)
4 print(b)
5 c=set({1,2,3})
6 print(c)
7 d=set({hello python})
8 print(type({hello }))
9 print(d)

显示结果

1 {1, 2, 3}
2 {h, l, e,  , p, n, y, o, t}
3 {1, 2, 3}
4 <class set>
5 {hello python}
假设a=set([1,2,3])
add 为set集合添加一个元素后,替换掉原来的对象 a.add(4) print(a) 输出{1,2,3,4}
remove 为set集合去掉一个元素后,替换掉原来的对象,若被替换的元素不在set集合内,将会报错

a.remove(2)  print(a)输出

{1,3}

 

 

 

 

 

 

 

小知识点: set集合可以看做是数学上的无序和无重复元素的集合,因此两个集合之间可以做数学意义上的交集和并集

假设a=set([1,2,3]) b=set([1,3])
a&b 输出结果{1,3}
a|b 输出结果{1,2,3,4}

 

 

 

 

 

 

  

Pyython学习之set集合

原文:https://www.cnblogs.com/SunIan/p/9689003.html

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