set定义
集合(set) 是一个无序的不重复的元素序列,能够去重复,删除重复项使用{},或者set()函数穿件,与dict的符号一样。空集合必须使用set(),因为{}是用来创建空字典dictset中的数据一定要是不可变数据,否则报错TypeError: unhashable type: 'list'
# all set
s1 = {'one',1,12,1,23,23,'one','two',('he','j')}
print(s1) #{'one', 1, ('he', 'j'), 12, 23, 'two'}
#无顺序输出
# 不能有可变数据?
#s2 = {'1','2',([1,2,3,4])}TypeError: unhashable type: 'list'
#s2 = {1,2,{1:1}}TypeError: unhashable type: 'dict'
#s1 = {1,2,{1,2}}#TypeError: unhashable type: 'set'
s2 = {}
print(type(s2))#
s3 = set()
print(s3,type(s3))#set()
集合是无序集合,不记录元素的位置或插入顺序。因此,不支持索引、切片或其他类似于序列的行为。因此没有切片、下标获取元素,以及一些特定的方法append等
Like other collections, sets support x in set, len(set), and for x in set. Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior.
set 成员运算符 以及 运算
set能够使用in/not in 来判断元素是否在集合内
Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. (For other containers see the built-in dict, list, and tuple classes, and the collections module.) 常见的用途包括成员资格测试、从序列中删除重复项,以及计算诸如交集、并集、差分和对称差分等数学操作。(对于其他容器,请参阅内置的dict、list和tuple类,以及collections模块。)
两个集合之间能够进行运算+ - & ^ ,能够对成员进行操作。交集、并集、查分、对称查分(求反) - :a -b : a删除b中的元素。b -a :b删除a中的元素。difference | : a | b : a 与b 的所有元素,相当于+,但是这里不能使用+ *操作符哦,因为是无序,没有索引,所以不知道 union & : a & b :a,b中都有的元素 intersection ^ : a ^ b :a、b中只有一方含有的元素。 symmetric_difference(other)
# 只有一方有的元素
s3 = {'a','b','c','d','e','i'}
s4 = set('abcfgtrdshssjs')
print(s3 -s4)# {'e'} s3中s4不包含的元素
print(s4-s3) #{'t', 'j', 's', 'h', 'g', 'f', 'r'}
#s4扣除s3的元素
#print(s3+s4) TypeError: unsupported operand type(s) for +: 'set' and 'set'
# 没有这个功能
#print(s3*3)TypeError: unsupported operand type(s) for *: 'set' and 'int'
print(s3|s4) #s3 s4 所有元素 {'g', 'c', 's', 't', 'f', 'b', 'h', 'e', 'r', 'a', 'j', 'd'}
print(s3 & s4) #{'a', 'd', 'b', 'c'} 都有的元素
print(s3 ^ s4) #{'r', 'e', 'h', 'g', 't', 's', 'f', 'i', 'j'}
# 只有一方有的元素
#s4.append('12')
没有append等方法,因为是无序列表,没有索引,所以对于序列的操作都无效。
set实例操作/frozenset实例操作
len(s)返回元素的长度
-属于内置函数 ,不属于set实例哦
print(len(s3))#6
in / not in 元素是否在集合中
in/not in 判断的是单个元素是否在集合中,如果是元组要注意括号,直接使用逗号分隔,会被识别为两句话哦!
# in/not in
s2 = {'one',1,12,1,23,23,'one','two',('he','j')}
print('one' in s2) # true
print(('he','j') in s2) #true
print(1,12 in s2) #1 true
isdisjoint(other) 是否无交集 是否有与其他元素相同的元素
返回bool型,两个数据是交集为空集的时候,返回true,否则返回false
Return True if the set has no elements in common with other. Sets are disjoint if and only if their intersection is the empty set.
#:如果集合中没有与其他元素相同的元素,则返回True,当且仅当它们的交集是空集时,集合是不相交的。
# 就是空集的时候,返回true。
set集合拥有isdisjoint(other)方法,other包含所有数据类型,只判断是否与set集合有无重复。
s5 = {'a','b','c'}
s6 ={'a'}
s7 ={'d'}
s8 = [1,2,3]
s9 = ('a','b')
s10 = 'ab'
print(s5.isdisjoint(s6))#false
print(s5.isdisjoint(s7))#true
print(s5.isdisjoint(s8))#true
print(s5.isdisjoint(s9))#false
print(s5.isdisjoint(s10))#false
print(s5.isdisjoint('1'))#true
issubset(other) 是否所有的元素都含有
判断集合的所有元素是否都包含在集合中,返回bool,如果都存在则表示为子集,返回true,否则返回false。x.issubset(other)other可以包含所有的数据元素,但是注意主导元素x必须是set集合.在使用的时候,忽略数据类型,只是单纯的对元素本身数据进行比较,必须要每一个相当于 <=
s5 = {'a','b','c'}
s6 ={'a'}
s7 ={'d'}
s8 = [1,2,3]
s9 = ('a','b')
s10 = 'ab'
print(s5.issubset(s6))#false
print(s6.issubset(s5))#true 注意包含关系
print(s7.issubset(s5))#false
#print(s8.issubset(s5)) AttributeError: 'list' object has no attribute 'issubset'
print(s5.issubset(s8))#false
print(s6.issubset(s9))#true
print(s6.issubset(s10))#true
# 纯粹判断元素是否属于子集
issuperset(other)
x.issuperset(y)判断是否所有的元素都包含在集合中,x是y的父类,x中有所有y的元素。x.issubset(y)中x是y的子类,y中有x的所有元素。返回bool 如果所有元素一样,那么就返回true同样x只能为set,因为只有set具有这类属性,y可以是任意元素。
s5 = {'a','b','c'}
s6 ={'a'}
s7 ={'d'}
s8 = [1,2,3]
s9 = ('a','b')
s10 = 'ab'
print(s5.issuperset(s6))#true
print(s6.issuperset(s5))#false
#print(s9.issuperset(s5))AttributeError: 'tuple' object has no attribute 'issuperset'
print(s5.issuperset(s8))#false
print(s5.issuperset(s9))#true
print(s5.issuperset(s10))#true
union(*others) 合并集合并且去重
s.union(others) others 表示多个数据,能够合并在一个集合中,并且去重。返回新集合,不会影响别的集合,会是一个深拷贝。不会相互影响合并的元素必须是可迭代的可以合并多个元素,逗号隔开即可。相当于|运算符
ss1 = {'a',1}
ss2 = 2
ss3 = 'two'
ss4 ={'33'}
ss5 = [5,6,'77']
ss6 =('88',11,2,3)
ss7 = {2:'haha',3:'sds'}
#print(ss1.union(ss2)) #TypeError: 'int' object is not iterable
# 需要迭代器?
print(ss1.union(ss3)) #{'o', 1, 'w', 'a', 't'}
print(ss1.union(ss4))#{1, 'a', '33'}
print(ss1.union(ss5)) #{1, 5, 6, '77', 'a'}
print(ss1.union(ss6)) #{1, 2, 3, 11, 'a', '88'}
print(ss1.union(ss7)) #{'a', 1, 2, 3} 字典是合并key
ss8 = ss1.union(ss4)
print(ss1.union(ss3)) #{1, 'w', 't', 'o', 'a'}
print(ss8) #{1, '33', 'a'}
ss9 = ss1.union(ss5)
print(ss9)#{1, 5, 6, 'a', '77'}
ss5[1]='yyyyyyy'
print(ss9) # 深拷贝
#print(set('12').union(1.1)) #TypeError: 'float' object is not iterable
print(set('12').union('a')) #{'a', '2', '1'}
print(ss1.union(ss3,ss4,ss5)) #{1, 'a', '77', 5, 'w', 't', '33', 'yyyyyyy', 'o'}
intersection(*other)
x.intersection(y1,y2...) 返回一个新的集合set,里面是所有元素中,重复的元素组成的集合当没有重复的元素,返回空集合set()深拷贝,更改后,不影响使用。y必须是可迭代的数据,同样是一样的数据相当于&
# intersection
ss1 = {'a',1,6}
ss2 = 2
ss3 = 'two'
ss4 ={'33'}
ss5 = [5,3,'77','a',1]
ss6 =('88',11,2,3)
ss7 = {2:'haha',3:'sds'}
ss8 = ss1.intersection(ss5)
print(ss8)#{1,'a'}
ss5[1]=6
print(ss8) #{1,'a'}
ss8 = ss1.intersection(ss5,ss6)
print(ss8) #set()
#print(ss1.intersection(ss2)) #TypeError: 'int' object is not iterable
difference(*other)
返回一个新集合,该集合中的元素在其他集合中不存在。x.difference(y) x在y中不存在的,则返回。y的参数是可迭代的才可运行如果y是dict字典,以key来作比较相当于-
# intersection
ss1 = {'a',1,6,2}
ss2 = 2
ss3 = 'two'
ss4 ={'33'}
ss5 = [5,3,'77','a',1]
ss6 =('88',11,2,3)
ss7 = {2:'haha',3:'sds'}
#print(ss1.difference(ss2)) #TypeError: 'int' object is not iterable
print(ss1.difference(ss3)) #必须是集合 {'a', 1,2, 6}
print(ss1.difference(ss4))#{a 16}
print(ss4.difference(ss1))#{33}
print(ss1.difference(ss5))#{6}
print(ss1.difference(ss7)) # dict 比对key
symmetric_difference(other)
返回一个新集合,表示只有一方具有的元素,不存在同时存在的元素。相当于^x. symmetric_difference(other) othe是数据是可迭代的,可以是任何可迭代数据dict以key参与
ss1 = {'a',1,6,2}
ss2 = 2
ss3 = 'two'
ss4 ={'33'}
ss5 = [5,3,'77','a',1]
ss6 =('88',11,2,3)
ss7 = {2:'haha',3:'sds'}
#print(ss1.symmetric_difference(ss2))
print(ss1.symmetric_difference(ss3)) #{1, 2, 6, 'w', 'a', 't', 'o'}
print(ss1.symmetric_difference(ss7))#{1, 3, 6, 'a'} key
copy 复制 浅拷贝
s.copy()返回一个浅拷贝内容。由于set集合是可变数据类型,copy后id值改变,有因为set数据内,只能有不可变数据,因此就算添加,添加的也是不可变数据,也就是id值会改变,因素相当于另一层意思的深拷贝拷贝详情可以看另一个文章~
#copy
ss1 = {'a',1,6,2}
ss2 = 2
ss3 = 'two'
ss4 ={'33'}
ss5 = [5,3,'77','a',1]
ss6 =('88',11,2,3)
ss7 = {2:'haha',3:'sds'}
ss8 = ss1.copy()
print(ss8)#{1, 'a', 2, 6}
ss1.add(ss6) # 集合内容只能不可变
print(ss1) #{1, 2, 6, 'a', ('88', 11, 2, 3)}
#ss8= ss1.copy()
print(ss8) #{'a', 2, 1, 6} #
ss1.add(12)
print(ss1) #{1, 'a', 2, 6, 12, ('88', 11, 2, 3)}
print(ss8) #{1, 'a', 2, 6}
print(id(ss1),id(ss8)) #140559882689000 140559882688104
注意点
Note, the non-operator versions of union(), intersection(), difference(), and symmetric_difference(), issubset(), and issuperset() methods will accept any iterable as an argument.
# 上面五个方法都是可以接受可迭代数据作为参数的。
In contrast, their operator based counterparts require their arguments to be sets.
# 相反,基于运算符的对应项要求它们的参数是集合。 也就是主要还是set集合
This precludes error-prone constructions like set('abc') & 'cbs' 3in favor of the more readable set('abc').intersection('cbs').
#print(set('abc').intersection('cbs'))#cb & 都有的 都有的
Both set and frozenset support set to set comparisons.
#set和frozenset都支持set到set的比较。
Two sets are equal if and only if every element of each set is contained in the other (each is a subset of the other).
#当且仅当每个集合的每个元素都包含在另一个集合中的时候,两个集合是相等的(每个元素都是另一个集合的子集)。
A set is less than another set if and only if the first set is a proper subset of the second set (is a subset, but is not equal). A set is greater than another set if and only if the first set is a proper superset of the second set (is a superset, but is not equal).
#一个集合小于另一个集合,当且仅当第一个集合是第二个集合的一个适当子集(是一个子集,但不相等)。一个集合大于另一个集合当且仅当第一个集合是第二个集合的一个适当的超集(是一个超集,但不是相等的)
# 以上说的就是subset 以及 superset的方法
Instances of set are compared to instances of frozenset based on their members. For example, set('abc') == frozenset('abc') returns True and so does set('abc') in set([frozenset('abc')]).
#将set实例与基于其成员的frozenset实例进行比较。例如,set('abc') == frozenset('abc')返回True, set('abc')中的set('abc')也是如此([frozenset('abc')])。
The subset and equality comparisons do not generalize to a total ordering function. For example, any two nonempty disjoint sets are not equal and are not subsets of each other, so all of the following return False: ab.
#子集和等式比较不能泛化为总的排序函数。例如,任何两个非空的不相交集都是不相等的,并且不是彼此的子集,因此所有的下列语句都返回False: ab。
Since sets only define partial ordering (subset relationships), the output of the list.sort() method is undefined for lists of sets.
#因为集合只定义了部分排序(子集关系),所以list.sort()方法的输出对于集合的列表是未定义的。 所以sort不能使用吗? 因为是不排序的
Set elements, like dictionary keys, must be hashable.
#集合元素,比如字典键,必须是可耐洗的。 我记得是不可变的。。
Binary operations that mix set instances with frozenset return the type of the first operand. For example: frozenset('ab') | set('bc') returns an instance of frozenset.
#将set实例与frozenset混合的二进制操作返回第一个操作数的类型。例如:frozenset('ab') | set('bc')返回一个frozenset实例。
The following table lists operations available for set that do not apply to immutable instances of frozenset:
下表列出了不应用于frozenset的不可变实例的可用于set的操作:
不应用frozenset应用set的操作
所以上面的操作都能适用于frozenset类型和set类型,以下只能操作set类型。
update(*other)
更新集合,添加来自所有其他元素的元素。同时满足去重的作用。无返回值,只会直接更新。更新的数据也必须是可迭代的,可以同时更新多个,用逗号隔开即可。如果数据有dict字典,那么会使用keyunion也是合并,返回新字典
#update
ss1 = {'a',1,6,2}
ss2 = 2
ss3 = 'two'
ss4 ={'33'}
ss5 = [5,3,'77','a',1]
ss6 =('88',11,2,3)
ss7 = {2:'haha',3:'sds'}
#ss8 = ss1.update(ss2)
ss8=ss1.update(ss3)
print(ss8)#None
print(ss1) #{1, 2, 6, 't', 'w', 'o', 'a'}
ss1.update(s4,s5)
print(ss1) #{1, 2, 'a', 6, 's', 'h', 'o', 'g', 'w', 'r', 'c', 'j', 'b', 'f', 't', 'd'}
ss1.update(ss7)
print(ss1) # key
intersection_update(*other)
intersection = | ,合并所有重复元素,返回重复集合,返回的是新集合intersection_update 更新集合,移除不重复的集合,剩下重复的元素,无返回值能有多个参数,类型要是可迭代的
ss1 = {1,2,3}
ss2 = {3,4,5}
print(ss1.intersection(ss2))#{3} new set
ss1.intersection_update(ss2)#{3}
print(ss1)#del repeat date
difference_update(*other)
difference = -,减去含有的元素,返回的是新集合difference_update 直接删除元素中含有的元素,无返回值。能有多个参数,类型要是可迭代的。
ss1 = {1,2,3}
ss2 = {3,4,5}
print(ss1.difference(ss2))#{1,2}
ss1.difference_update(ss2)
print(ss1)#{1,2}
symmetric_update(*other)
symmetric_difference ,在所有集合中单独存在的元素,返回一个新集合symmetric_difference_update :移除当前集合中在另外一个指定集合相同的元素,并将另外一个指定集合中不同的元素插入到当前集合中。移除并插入参数可以多个,但是要可迭代,元素本身也可以作为参数哦。
ss1 = {1,2,3}
ss2 = {3,4,5}
print(ss1.symmetric_difference(ss2)) #{1,2,4,5}
ss1.symmetric_difference_update(ss2)
print(ss1) #{1,2,4,5}
add(elem)
添加元素去set中,无返回值添加的元素需要满足,set的定义。内部元素只能是不可变元素,dict字典也不行,不会只获取key。
ss1 = {'one'}
ss1.add(1)
print(ss1)#{1,'one'}
ss1.add(1+2j)
print(ss1)#{1,'one',1+2j}
ss1.add('sh')
print(ss1) #{'one', 'sh', 1, (1+2j)}
ss1.add((1,2,3))
print(ss1) #{1, (1+2j), 'one', 'sh', (1, 2, 3)}
#ss1.add([1,2,3])
#print(ss1) #TypeError: unhashable type: 'list'
# 不可加可变元素
#ss1.add({'hello'})
#print(ss1)TypeError: unhashable type: 'set'
#ss1.add({1:'hh',33:'ddf'})
#print(ss1) #TypeError: unhashable type: 'dict'
remove(elem)
移除制定元素,移除一个不存在的元素时会发生错误keyError,而 discard() 方法不会。必须要带被删除的元素,否则TypeError: remove() takes exactly one argument (0 given),所以必须要有参数,只有一个参数返回移除元素??? 测试的时候,是返回None哦!,所以无返回值
#remove
ss1 = {1,2,3,4,5}
#print(ss1.remove())#TypeError: remove() takes exactly one argument (0 given)
print(ss1.remove(3))#none?
fruits = {"apple", "banana", "cherry"}
test=fruits.remove("banana")
print(test)#none
print(fruits) #{'apple', 'cherry'}
discard(elem)
删除指定元素,移除一个不存在的元素不会发生错误keyError必须要带被删除的元素,否则报错,至少一个无返回值
ss1 = {1,2,3,4,5}
ss1.discard(1)
print(ss1)#{2,3,4,5}
ss1.discard(89)
print(ss1)#{2,3,4,5} 不影响 不报错
pop()
随机删除元素,返回移除的元素如果set集合为空,那么会KeyError:pop from an empty set
ss1= {1,'one','hha',34,'a',4,56}
ss2 = ss1.pop()
print(ss2)#1
ss3 =ss1.pop()
print(ss3)#34
ss4 = ss1.pop()
print(ss4)#hha
ss5 =set()
#print(ss5.pop()) #KeyError: 'pop from an empty set'
clear
清空所有元素,无返回值原本是空集合也不会影响,同样返回一个set()
fruits = {"apple", "banana", "cherry"}
fruits.clear()
print(fruits)
ss5 =set()
#print(ss5.pop()) #KeyError: 'pop from an empty set'
ss5=set()
print(ss5)#set()
ss5.clear()#set()
set与frozenset的异同
set(可变集合),无序排列,不重复,并且可变。内部数据不可变frozenset是冻结集合,不可变,可以作为字典的key,也可以作为集合的元素,一旦创建不能更改,无add,remove方法set()和 frozenset()工厂函数分别用来生成可变和不可变的集合。如果不提供任何参数,默认会生成空集合。如果提供一个参数,则该参数必须是可迭代的能够使用上面所诉,set和frozenset共有的方法,后面set特有的方法不可以使用。能够in/not infrozenset 不能改变或删除元素,是不可变的set可与frozenset比较,==,判断元素数据是否相同。能够使用- | & ^ 计算,也能够与set一起进行计算,但是要注意,计算结果的类型以第一个操作数类型为准参考文献 点击这里
# set/ frozenset
s = set('abcd')
ss = {1,2,3} # 直接创建
print(s) #{'b', 'a', 'd', 'c'} 无序
print(type(s))#
f = frozenset('abcd')
print(f)#frozenset({'b', 'c', 'd', 'a'}) 也是无序的
print(type(f)) #
# 冰冻set
#set可变 frozenset不可变
s.add('e')
s.remove('a')
print(s) #{'d', 'e', 'b', 'c'}
#f.add('e') 不可修改
#print(f) AttributeError: 'frozenset' object has no attribute 'add'
#in /not in ok
print('b' in s)#true
print('b' in f)#true
#set == frozenset ?? 不同
print(s == f)#false
a = frozenset(s)
print(a) #frozenset({'d', 'b', 'e', 'c'})
print(s) #{'c', 'b', 'd', 'e'}
print(a==s)#true 判断值是否相等
f1 = frozenset('123')
s1 = set('123')
print(f1,s1) #frozenset({'3', '1', '2'}) {'3', '1', '2'}
print(f1==s1) #true 判断元素相等
print(frozenset('ab')) #都具有上述的方法
print(len(f1))#3 okk
# 支持for
for i in f1:
print(i)#312
# | - & ^ 返回的海斯frozenset类型
f1 = frozenset('123')
s1 = set('16')
f2 = frozenset('134')
print(f1-f2)# frozenset({'2'})
print(f2-f1) #frozenset({'4'})
print(f1 | f2) #frozenset({'1', '3', '4', '2'})
# 去重
print(f1&f2)#frozenset({'3', '1'})
print(f1^f2) #frozenset({'2', '4'})
print(f1-s1) #frozenset({'3', '2'})
print(s1-f1) #{'6'} set类型
# 以第一个操作数的类型为准 set和frozenset可以一起操作