十八、集合
1、集合最大的特性是:唯一性,集合中所有的元素都应该是独一无二的,并且也是无序的。
2、创建集合
1)使用花括号{}
>>>{"FishC","Python"}
{'FishC', 'Python'}
2)集合推导式:无序随机
>>>{s for s in "FishC"}
{'i', 'C', 's', 'F', 'h'}
3)使用类型构造器
>>>set("FishC")
{'i', 'C', 's', 'F', 'h'}
注意:由于集合是无序的,所以我们不能使用下标索引的方式来对它进行访问
3、in和not in:判断某个元素是否存在于集合中
>>>s = set("FishC")
>>>'C' in s
True
>>>''c' not in s
True
4、访问集合中的元素,可以使用迭代的方式
>>>for each in s:
>>> print(each)
i
C
s
F
h
5、去重:利用集合的唯一性
>>>set([1,1,2,3,5])
{1, 2, 3, 5}
6、检测一个列表中是否存在相同的元素
>>>s = [1,1,2,3,5]
>>>len(s) == len(set(s))
False
7、集合的各类方法:(注意others说明支持多个参数,other表示只支持一个参数)
方法 | 含义 |
s.copy() | 返回s集合的一个浅拷贝 |
s.isdisjoint(other) | 如果s集合中没有于other容器存在共同的元素,那么返回True,否则返回False |
s.issubset(other) | 如果s集合是other容器的子集,那么返回True,否则返回False |
s.issuperset(other) | 如果s集合是other容器的超集,那么返回True,否则返回False |
s.union(*others) | 返回一个新集合,其内容是s集合与other容器的并集 |
s.intersection(*others) | 返回一个新集合,其内容是s集合与other容器的交集 |
s.difference(*others) | 返回一个新集合,其内容是存在于s集合中,但不存在于other容器中的元素 |
s.symmetric_difference(other) | 返回一个新集合,其内容是排除掉s集合和other容器中共有的元素后,剩余的所有元素 |
举例:
#s.copy():浅拷贝
>>>t = s.copy()
>>>t
[1, 1, 2, 3, 5]
#isdisjoint():检测两个集合之间是否毫不相干,有无共同的元素
>>>s = set("FishC")
>>>s
>>>{'i', 'C', 's', 'F', 'h'}
>>>s.isdisjoint(set("Python"))
#有一个交集h
False
#issubse():检测集合是否另一个集合的子集
子集:对于两个集合A、B,如果集合A中任意一个元素都是集合B中的元素,我们就说这两个集合有包含关系,称集合A为集合B的子集。
>>>s.issubset("FishC.com.cn")
True
#issuperset():检测集合是否是另一个集合的超集
超集:对于两个集合A、B,如果集合B中任意一个元素都是集合A中的元素,我们就说这两个集合有包含关系,称集合A为集合B的超集
>>>s.issuperset("Fish")
True
#计算当前集合和其他对象共同构建的并集、交集、差集以及对称差集
#union():并集:对于两个集合A、B,把他们所有的元素合并在一起组成的集合,叫做集合A与集合B的并集
>>>s.union({1,2,3})
{1, 'i', 'F', 2, 3, 'h', 'C', 's'}
#intersection():交集:对于两个集合A、B,由所有属于集合A且属于集合B的元素所组成的集合,叫做集合A与集合B的交集
>>>s.intersection("Fish")
{'F', 's', 'i', 'h'}
#difference():差集:对于两个集合A、B,由所有属于集合A且不属于集合B的元素所组成的集合,叫做集合A与集合B的差集
>>>s.difference("Fish")
{'C'}
#symmetric_difference():对称差集:对于两个集合A、B,先排除集合A与集合B的所有共同元素,由剩余的元素组成的集合,叫做集合A与集合B的对称差集
>>>s.symmetric_difference("Python")
{'y', 'i', 'o', 'C', 'n', 's', 't', 'F', 'P'}
8、运算符运算集合
1)子集 <=
>>>s <= set("FishC")
True
2)真子集 <
>>>s < set("FishC")
False
>>>s < set("FishC.com.cn")
True
3)超集 >=
>>>s >= set("FishC")
True
4)真超集 >
>>>s > set("FishC")
False
5)并集 | (管道符)
>>>s | {1,2,3} |set ("Python")
{'y', 1, 'i', 2, 3, 'o', 'C', 'n', 's', 't', 'F', 'h', 'P'}
6)交集 &
>>>s & set("Php") &set("Python")
{'h'}
7)差集 -
>>>s - set("Php") - set("Python")
{'i', 's', 'F', 'C'}
8)对称差集 ^ (脱字符)
>>>s ^ set("Python")
{'y', 'i', 't', 'o', 'C', 'n', 's', 'F', 'P'}
注意:使用运算符的话,符号两边都必须是集合类型的数据才行
>>>s <= "FishC"
Traceback (most recent call last):
File "<pyshell#102>", line 1, in <module>
s <= "FishC"
TypeError: '<=' not supported between instances of 'set' and 'str'
9、集合分为可变对象set()和不可变对象frozenset()
>>>t = frozenset("FishC")
>>>t
frozenset({'i', 'C', 's', 'F', 'h'})
#因为集合的唯一性,所以列表中的1被去重了,又因为集合的无序性,所有加入的23,有可能会出现3在2前面
>>> s.update([1,1],"23")
>>> s
{'3', 1, 'F', 'C', 's', '2', 'i', 'h'}
#frozenset的集合是不可变的,如果进行改变会报错
>>> t = frozenset("FishC")
>>> t
frozenset({'F', 'C', 's', 'i', 'h'})
>>> t.update([1,1],"23")
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
t.update([1,1],"23")
AttributeError: 'frozenset' object has no attribute 'update'
2)intersection_update(*others)、difference_update(*others)、symmetric_difference_update(others)
以交集、差集和对称差集的方式来更新集合,会将结合的值修改。
>>> s.intersection_update("FishC")
>>> s
{'F', 'C', 's', 'i', 'h'}
>>> s.difference_update("Php","Python")
>>> s
{'F', 'C', 's', 'i'}
>>> s.symmetric_difference_update("Python")
>>> s
{'F', 'n', 'C', 'o', 'y', 's', 'i', 'P', 't', 'h'}
3)add(elem):往集合里添加某个数据
注意区别:uppdate方法,传入字符串是迭代获取其中每个字符,作为元素插入到集合中;
add方法传入字符串,是将整个字符串作为一个元素插入到集合中。
>>> s.add("45")
>>> s
{'45', 'F', 'n', 'C', 'o', 'y', 's', 'i', 'P', 't', 'h'}
4)remove(elem)、discard(elem):删除某个元素
注意:remove(elem)、discard(elem)两者的区别是如果指定的元素不存在,remove方法会抛出异常,而discard方法则会静默处理。
>>> s.remove("瓦特")
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
s.remove("瓦特")
KeyError: '瓦特'
>>> s.discard("瓦特")
>>> s
{'45', 'F', 'n', 'C', 'o', 'y', 's', 'i', 'P', 't', 'h'}
5)pop()方法用于随机从集合中弹出一个元素
>>> s.pop()
'45'
>>> s.pop()
'F'
>>> s.pop()
'n'
>>> s
{'C', 'o', 'y', 's', 'i', 'P', 't', 'h'}
6)clear():清空集合
>>> s.clear()
>>> s
set()
10、可哈希:如果一个对象是可哈希的,那么要求它的哈希值,必须在其整个程序的生命周期中保持不变。
想要正确的创建集合和字典,刚性需求,要求字典的键和集合的元素都必须是可哈希的。
1)hash(object)函数:获取对象的哈希值
1.如果对一个整数进行哈希,求其哈希值,那么它的值永远都等于它的自身
2.如果两个对象的值是相等的,尽管他们是不同的对象,那么它们的哈希值也是相等的
>>> hash(1)
1
>>> hash(1.0)
1
>>> hash(1.001)
2305843009213441
Python中大多数不可变的对象都是可哈希的。而不可变的对象,则是不可哈希的。
>>> hash("FishC")
6273830742685173857
>>> hash([1,2,3])
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
hash([1,2,3])
TypeError: unhashable type: 'list'
>>> hash((1,2,3))
529344067295497451
2)字典的键和集合中的元素都必须是可哈希的。
>>> {"Python":520,"FishC":1314}
{'Python': 520, 'FishC': 1314}
>>> {[1,2,3]:"FishC"}
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
{[1,2,3]:"FishC"}
TypeError: unhashable type: 'list'
>>> {"Python","FishC",520,1314}
{520, 'FishC', 1314, 'Python'}
>>> {"Python","FishC",520,1314,[1,2,3]}
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
{"Python","FishC",520,1314,[1,2,3]}
TypeError: unhashable type: 'list'
3)集合是不可嵌套的,但可以使用frozenset来实现
>>> x = {1,2,3}
>>> y = {x,4,5}
Traceback (most recent call last):
File "<pyshell#36>", line 1, in <module>
y = {x,4,5}
TypeError: unhashable type: 'set'
>>> x =frozenset(x)
>>> y = {x,4,5}
>>> y
{frozenset({1, 2, 3}), 4, 5}