集合数据类型的操作

来源:互联网 发布:怎么用python画图 编辑:程序博客网 时间:2024/06/05 03:31

1.集合是0个或者多个变量(对象引用)的无序组合,这些变量所引用的对象都是可哈希的(字符串、元组、数字等不可变数据类型),当加入一些诸如列表、字典、可变集合等可变数据类型时,会报错TypeError: unhashable type: ‘list’|’set’|’dict’。
由于集合是可变的,因此很容易添加或者移除数据项,但由于其中的项是无序的,因此集合无索引概念 也不能分片。

2.创建空集合只能用s=set(),因为{}是创建空字典;支持len和in 、not in成员关系测试

3.集合支持方法
(1)s.add(x)
Add an element to a set.This has no effect if the element is already present.
(2)s.clear()
Remove all elements from this set.
(3)s.copy()
Return a shallow copy of a set.浅拷贝只是值的复制,是新建了一个集合
(4)s.discard(x)
Remove an element from a set if it is a member.If the element is not a member, do nothing.
(5)s.remove(x)
Remove an element from a set; it must be a member.If the element is not a member, raise a KeyError
(6)s.pop()
Remove and return an arbitrary set element.删除随机项,Raises KeyError if the set is empty.
注意:(4)(5)(6)的区别

(7)s.isdisjoint(t)
Return True if two sets have a null intersection.两集合无交集就返回True
(8)s<=t 等价于s.issubset(t)
s是t的子集返回True
(9)s>=t 等价于s.issuperset(t)
s是t的超集返回True

(10)s-t 等价于s.difference(t)
返回一个新集合,元素为在s中不在中
(11)s -= t 等价于s.difference_update(t)
直接修改s:s只保留存在s不存在t中的元素

(12)s&t等价于s.intersection(t)
集合交集
(13)s &= t等价于 s.intersection_update(t)
把s更新为s和t的交集
Update a set with the intersection of itself and another

(14)s|t 等价于s.union(t)
返回一个新集合,集合并集
(15)s |= t 等价于s.update(t)
直接修改s为s与t的并集

(16)s^t等价于 s.symmetric_difference
返回t一个新集合,内容为集合s、t并集-s、t交集
即s^t=s|t-s&t
(17)s ^=t 等价于 s.symmetric_difference_update
将s修改为s|t-s&t

4.集合生成式
{s for s in ‘abcde’ if s not in ‘cd’} == >{‘a’, ‘b’, ‘e’}

5.固定集合
一旦被创建就不能改变,创建方法:
空的固定集合:s=frozenset()
非空的固定集合: s=frozenset([1,2,3,4])
固定集合是不可变数据类型,那么其支持的方法与操作符所产生的结果不能影响固定集合本身
固定集合支持的方法:
copy,isdisjoint,issubset,issuperset,
union(|),intersection(&),difference(-)
symmetric_difference(^),

原创粉丝点击