python中set常用操作

python的set和其他语言类似, 是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素. 集合对象还支持union(联合), intersection(交), difference(差)和sysmmetric difference(对称差集)等数学运算

sets 支持 x in set, len(set),和 for x in set。作为一个无序的集合，sets不记录元素位置或者插入点。因此，sets不支持 indexing, slicing, 或其它类序列（sequence-like）的操作。

in [2]: a = set()
in [3]: a
out[3]: set()
in [4]: type(a)
out[4]: set
in [5]: b = set([1, 3])
in [6]: b
out[6]: {1, 3}
in [7]: type(b)
out[7]: set
in [8]: b.update(2)
—————————————————————————
typeerror traceback (most recent call last)
in ()
—-> 1 b.update(2)
typeerror: ‘int’ object is not iterable
in [9]: b.update({2})
in [10]: b
out[10]: {1, 2, 3}
in [11]: b.update([4])
in [12]: b
out[12]: {1, 2, 3, 4}
in [13]: a.di
in [13]: a.dif
a.difference a.difference_update
in [13]: a.difference(b)
out[13]: set()
in [14]: a
out[14]: set()
in [15]: b.difference(a)
out[15]: {1, 2, 3, 4}
in [16]:

—————————————————————————
typeerror traceback (most recent call last)
in ()
typeerror: unhashable type: ‘set’
in [18]: a
out[18]: {4}
in [19]: a.issu
a.issubset a.issuperset
in [19]: a.issubset(b)
out[19]: true
in [20]: a.remove(4)
in [21]: a
out[21]: set()
in [22]: a.union(b)
out[22]: {1, 2, 3, 4}
in [23]: a
out[23]: set()
in [24]: b
out[24]: {1, 2, 3, 4}
in [25]: b.pop()
out[25]: 1
in [26]: a.copy(b)
—————————————————————————
typeerror traceback (most recent call last)
in ()
—-> 1 a.copy(b)
typeerror: copy() takes no arguments (1 given)
in [27]: a.copy()
out[27]: set()
in [28]: c = a.copy()
in [29]: c
out[29]: set()
in [30]: a
out[30]: set()
—————————————————————————
typeerror traceback (most recent call last)
in ()
typeerror: unhashable type: ‘set’
in [33]: c
out[33]: set()
in [34]: a
out[34]: {234}

in [35]: a.clear()
in [36]: a
out[36]: set()
in [39]: a = {1}
in [40]: b = {1, 2}
in [41]: a.intersection(b)
out[41]: {1}
in [43]: a
out[43]: {1}
in [44]: b = {1, 2, 3}
in [45]: a.union(b)
out[45]: {1, 2, 3}
in [45]: a.union(b)
out[45]: {1, 2, 3}
in [46]: a & b
out[46]: {1}
in [47]: a ^ b
out[47]: {2, 3}
in [48]: a – b
out[48]: set()
in [49]: b – a
out[49]: {2, 3}
in [50]: a > b
out[50]: false
in [51]: b > a
out[51]: true
in [52]: a == b
out[52]: false
in [53]: a != b
out[53]: true

Posted in 未分类