2022-05-04 集合

1、集合的定义:集合是无序的,创建集合有三种方式

set()

>>> a = set("Jason")
>>> a
{'o', 'a', 's', 'J', 'n'}

使用集合推导式

>>> b = {s for s in "Jason"}
>>> b
{'o', 'a', 's', 'J', 'n'}

使用花括号包含各类元素

>>> c = {'jason',120,'apple','android'}
>>> c
{120, 'jason', 'apple', 'android'}

因为集合是无序的,所以不能使用下标访问集合中的数据,可以使用 in 或者 not in 来判断一个元素是不是在集合中

>>> s = set("FishC")
>>> s[0]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    s[0]
TypeError: 'set' object is not subscriptable
>>> 'C' in s
True
>>> 'c' not in s
True

2、访问集合

如果想要访问集合中的元素,可以使用迭代的方式:

>>> for each in s:
...     print(each)
...
F
h
i
s
C

3、集合有去重的特性

>>> a = {1,1,2,2,3,5}
>>> a
{1, 2, 3, 5}
"""用集合来判断一个列表中是否包含相同的数据"""
>>> a = [1,1,2,2,3,5,6]
>>> len(a) == len(set(a))
False
>>> s = [1, 2, 3, 5]
>>> len(s) == len(set(s))
True

4、集合的各种方法:点这里

集合的拷贝

>>> t = s.copy()
>>> t
{'h', 's', 'i', 'F', 'C'}

检查两个集合是否毫无关联用 isdisjoint(other)方法:

>>> a = {"Jason"}
>>> b = {"fbi"}
>>> a.isdisjoint(b)
True
"""这个方法不要求b(传入的参数)必须是集合,但是调用这个方法的对象必须是集合"""
>>> a = "Jason"
>>> a.isdisjoint("FBI")
Traceback (most recent call last):
  File "<pyshell#1272>", line 1, in <module>
    a.isdisjoint("FBI")
AttributeError: 'str' object has no attribute 'isdisjoint'

>>> a = {"Jason"}
>>> a.isdisjoint("FBI")
True
>>> a.isdisjoint([1,2,3])
True
>>> a.isdisjoint((1,2,3))
True

issubset(other) 检查一个集合是不是other的子集

>>> a = {'Jason','Yang','Python'}
>>> a.issubset({'Jason','Yang','Python'})
True
>>> a.issubset({'Jason','Yang','Python','Learn'})
True
>>> a.issubset({'Jason','Yang'})
False

issuperset(other) 检查一个集合是不是other的超集

>>> a
{'Jason', 'Yang', 'Python'}
>>> a.issuperset({'Jason'})
True

并集 union(other)

返回调用union()方法的对象与other对象中所有的不重复的元素的集合

"""并集,就是将集合与其它集合的元素合并在一起,组成一个新的集合:"""
>>> a
{'Jason', 'Yang', 'Python'}
>>> a.union({1,2,3})
{'Jason', 1, 'Yang', 'Python', 2, 3}
>>> a.union([1,2,3])
{1, 2, 'Python', 3, 'Jason', 'Yang'}
>>> a.union((1,2,3))
{1, 2, 'Python', 3, 'Jason', 'Yang'}

交集 intersection(other)

返回调用intersection()方法的对象与other对象之间共存的元素的集合

>>> a = {i for i in "Jason"}
>>> a
{'o', 'a', 's', 'J', 'n'}
>>> a.intersection("python")
{'o', 'n'}

差集 difference(other)

返回调用difference()方法的对象里面有而other对象中没有的元素的集合

>>> a
{'o', 'a', 's', 'J', 'n'}
>>> a.difference("Python")
{'a', 's', 'J'}

union() intersection() difference() 都支持多参数

>>> s.union({1, 2, 3}, "Python")
{1, 2, 3, 'y', 'h', 'n', 'i', 'P', 's', 'o', 't', 'C', 'F'}
>>> s.intersection("Php", "Python")
{'h'}
>>> s.difference("Php", "Python")
{'s', 'C', 'F', 'i'}

对称差集 symmetric_difference(other)

返回一个other对象与调用symmetric_difference()方法的对象之间除了公共部分的其他元素的集合

"""这个方法只支持一个参数"""
>>> a
{'o', 'a', 's', 'J', 'n'}
>>> a.symmetric_difference("python")
{'t', 'y', 'a', 'h', 's', 'J', 'p'}

5、运算符小技巧

检测子集可以使用小于等于号(<=):

>>> a = {'Jason','Yang'}
>>> b = {'Jason','Yang','Apple'}
>>> a <= b
True

检测真子集我们可以使用小于号(<):

>>> a = {'Jason','Yang'}
>>> b = {'Jason','Yang','Apple'}
>>> a <= b
True
>>> a < b
True
"""真子集是不包含子集本身的,子集可能是两个相同的集合"""
>>> a = {'Jason','Yang'}
>>> b = {'Jason','Yang'}
>>> a < b
False
>>> a <= b
True

那么反过来,使用大于号(>)和大于等于号(>=)就是检测真超集和超集:

>>> b = {'Jason','Yang','Apple'}
>>> b > a
True
>>> b >= a
True
"""真超集是不包含父集本身的,超集可能是两个相同的集合"""
>>> a = {'Jason','Yang'}
>>> b = {'Jason','Yang'}
>>> a > b
False
>>> a >= b
True

并集使用管道符(|):

>>> s | {1, 2, 3} | set("Python")
{1, 2, 3, 'y', 'h', 'n', 'i', 'P', 's', 'o', 't', 'C', 'F'}

交集使用 and 符号(&):

>>> s & set("Php") & set("Python")
{'h'}

差集使用减号(-):

>>> s - set("Php") - set("Python")
{'s', 'C', 'F', 'i'}

对称差集使用脱字符(^):

>>> s ^ set("Python")
{'t', 'y', 'F', 's', 'P', 'C', 'n', 'o', 'i'}

使用运算符时 运算符两个的数据类型都必须是集合

集合1.png

6、集合的两种形态

可变集合set()

>>> a = set("Jason")
>>> a
{'o', 'a', 's', 'J', 'n'}
>>> a.update("Apple")
>>> a
{'A', 'o', 'a', 'l', 'e', 's', 'J', 'n', 'p'}

不可变集合frozenset()

>>> t.update([1, 1], "23")
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    t.update([1, 1], "23")
AttributeError: 'frozenset' object has no attribute 'update'

仅适用于 set() 对象的方法

update(*others) 方法使用 others 容器中的元素来更新集合:

>>> s = set("FishC")
>>> s
{'s', 'C', 'i', 'F', 'h'}
>>> s.update([1, 1], "23")
>>> s
{'s', 1, 'C', 'i', 'F', 'h', '3', '2'}

交集 update- intersection_update(*others)

"""谁调用了intersection_update(*others) 这个方法 就是update谁"""
>>> a
{'c', 'b', 'a'}
>>> b
{'e', 'o', 'a'}
>>> a.intersection_update(b)
>>> a
{'a'}
"""如果只是查看交使用intersection()方法,这样只是查看连个对象的交集,并不改变任何一个对象"""
>>> a.intersection(b)
{'a'}
>>> a
{'c', 'b', 'a'}
>>> b
{'e', 'o', 'a'}

差集 update- difference_update(*others)

"""谁调用了a.difference_update(b) 这个方法,结果返回是(a-(a与b相同的元素))并将上面的结果update给a """
>>> a = set("abc")
>>> b = set("aoe")
>>> a.difference_update(b)
>>> a
{'c', 'b'}

对称差集 update symmetric_difference_update(*others)

"""a.symmetric_difference_update(b)的结果是返回排除a与b 相同的部分剩余的全部元素,组合成一个集合并update给a"""
{'c', 'b', 'a'}
>>> b
{'e', 'o', 'a'}
>>> a.symmetric_difference_update(b)
>>> a
{'c', 'b', 'o', 'e'}

add()

给集合添加数据

>>> a = set("abc")
>>> a
{'c', 'b', 'a'}
>>> a.add('d')
>>> a
{'d', 'c', 'b', 'a'}
"""这里add(elem)对应的参数elem意思是“element”元素,不再是一个可迭代对象"""
>>> a = set("abc")
>>> a
{'c', 'b', 'a'}
>>> a.add("def")
>>> a
{'c', 'b', 'def', 'a'}

remove(elem)

"""在集合中删除一个元素"""
>>> a
{'c', 'b', 'def', 'a'}
>>> a.remove("def")
>>> a
{'c', 'b', 'a'}

discard(elem)

"""与remove不同的是,如果remove指定的元素不在原集合中,则会抛出异常 discard(elem)则不会有任何反应"""
>>> a
{'c', 'b', 'a'}
>>> a.remove('d')
Traceback (most recent call last):
  File "<pyshell#1638>", line 1, in <module>
    a.remove('d')
KeyError: 'd'
>>> a.discard('D')

pop()

"""pop()用于列表对象时,固定删除最后一个元素"""
>>> a = [1,2,3]
>>> a.pop()
3
>>> a.pop()
2
>>> a.pop()
1
"""元组对象没有pop()这个方法,用于字典对象时则必须指定一个key"""
>>> c = dict(zip([1,2,3],('a','b','c')))
>>> c
{1: 'a', 2: 'b', 3: 'c'}
>>> c.pop()
Traceback (most recent call last):
  File "<pyshell#1653>", line 1, in <module>
    c.pop()
TypeError: pop expected at least 1 argument, got 0
>>> c.pop(1)
'a'
>>> c.pop(3)
'c'
>>> c
{2: 'b'}
"""pop()用于集合时,则为随机删除集合中的一个数据"""
>>> a = set("Jason")
>>> a
{'o', 'a', 's', 'J', 'n'}
>>> a.pop()
'o'
>>> a.pop()
'a'
>>> a.pop()
's'
>>> a.pop()
'J'
>>> a.pop()
'n'
>>> a.pop()
Traceback (most recent call last):
  File "<pyshell#1666>", line 1, in <module>
    a.pop()
KeyError: 'pop from an empty set'
>>> a
set()
"""clear() 就是清空集合"""
>>> s
{'o', 'a', 's', 'J', 'n'}
>>> s.clear()
>>> s
set()

7、可哈希

>>> hash(1)
1
>>> hash(1.0)
1
>>> hash(1.001)
2305843009213441

Python 中大多数不可变对象是可哈希的,而那些可变的容器则不哈希:

>>> hash("FishC")
2090433017907150752
>>> hash([1, 2, 3])
Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    hash([1, 2, 3])
TypeError: unhashable type: 'list'

如果我们把列表换成元组,元组是不可变的对象,那就应该是可哈希的:

>>> hash((1, 2, 3))
529344067295497451

8、嵌套一个集合

>>> x
{1, 2, 3}
>>> y
frozenset({1, 2, 3})
>>> x = {y,4,5,6}
>>> x
{frozenset({1, 2, 3}), 4, 5, 6}
"""因为set集合是可变的,也就是unhashable,所以下面是错误的示范"""
>>> x = {1,2,3}
>>> x
{1, 2, 3}
>>> type(x)
<class 'set'>
>>> y = {x,4,5}
Traceback (most recent call last):
  File "<pyshell#1710>", line 1, in <module>
    y = {x,4,5}
TypeError: unhashable type: 'set'
集合2.png

注意

a.update("Jason")将会把{'J','a','s','o','n'}全插入a集合中

a.add("Jason")则置灰将"Jason"插入a集合

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1 集合的基本概念 在计算机科学中,集合(collection)是一组可变数量的数据项(也可能是0个)的组合,这些...
    小小小小河阅读 658评论 0 0
  • A set object is an unordered collection of distinct hasha...
    彼岸的渔夫阅读 301评论 0 0
  • 目录0.集合介绍1.集合的定义和初始化2.集合元素增加3.集合元素删除4.集合运算 0.集合介绍 非线性的数据结构...
    Stone_説阅读 413评论 0 1
  • set.isdisjoint 交集为空吗? 集合方法 set.isdisjoint(),Python 官方文档描述...
    MW明文阅读 197评论 0 0
  • 一.set 可变的,无序的,不重复的元素的集合 set 里面的元素必须可以hash set 可以迭代 set 不可...
    秋幻旎苏阅读 609评论 0 0