python 基础数据类型-集合set
set与序列list的区别是,set无序不重复,list 有序可重复
定义集合:用{}
再次总结一下,元组tuple是(),list是[],集合是{}
>>> type({1,2,3,4,5}) <class 'set'>
如何定义空集? type({}) <class 'dict'> 这肯定不行 得这样 >>> type(set()) <class 'set'>
与list相比 集合不支持下标操作,那更不可能支持切片操作
>>> {1,2,3}[2] <stdin>:1: SyntaxWarning: 'set' object is not subscriptable; perhaps you missed a comma? Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'set' object is not subscriptable >>> >>> {1,2,3}[0:2] <stdin>:1: SyntaxWarning: 'set' object is not subscriptable; perhaps you missed a comma? Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'set' object is not subscriptable
集合也支持len(),计算长度
集合是不包含重复的元素的
>>> len({1,2,3}) 3 >>> {1,2,3} {1, 2, 3} >>> {1,2,3,3} {1, 2, 3} >>> {1,2,3,4} {1, 2, 3, 4}
跟list tuple 一样,支持这种操作
>>> 1 in {1,2,3} True >>> 1 in [1,2,3] True >>> 1 in (1,2,3) True
支持差集合运算、交集运算、并集运算 >>> {1,2,3}-{1,2} {3} >>> {1,2,3}&{1,2} {1, 2} >>> {1,2,3}| {3,4} {1, 2, 3, 4}