pythoning——6、数据类型(set集合)

set集合是一种无序、无重合值、可迭代的数据集合。

set函数

set可以通过set()函数对序列进行强制转换为set类型的数据,也可以通过直接赋值的方式生成set类型数据:

>>> a = set((1,2,3,4,5))
>>> a
{1, 2, 3, 4, 5}
>>> a = {1,2,3,4,5}
>>> a
{1, 2, 3, 4, 5}

方法

通过函数dir(set)可以看到set的函数有哪些。

这里着重介绍一下几个常用函数

add

add方法是想set集合中添加元素

clear

clear清空set集

copy

与str中的copy相似,只能进行浅拷贝,需要用到deepcopy

>>> a
{1, 2, 3, 4, 5}
>>>
>>> a.add(7)
>>> a
{1, 2, 3, 4, 5, 7}

>>> a.clear()
>>> a
set()

>>> a = set((1,2,3,4,5))
>>> b = a.copy()
>>> b
{1, 2, 3, 4, 5}

different与difference_update

查找set1与set2中不一样的元素,前者返回不一样的值,后者对set1进行修改

>>> a = set((1,2,3,45))
>>> b = set((1,2,3,4))
>>> a.difference(b)
{45}
>>> a.difference_update(b)
>>> b
{1, 2, 3, 4}
>>> a
{45}
>>>

intersection,intersection_update

与different、difference_update用法结果相似,与之不同intersection、intersection_update查找的内容为俩元素的相同值。

>>> a = {1,2,3,4}
>>> b
{1, 3, 5, 7}
>>> a.intersection(a)
{1, 2, 3, 4}
>>> a.intersection(b)
{1, 3}
>>> a.intersection_update(b)
>>> a
{1, 3}

update

用set2对set1进行更新,set1既有值不变,添加set2中的新值

>>> b
{1, 2, 3, 4}
>>> a
{45}
>>> a.update(b)
>>> a
{1, 2, 3, 4, 45}

 pop,discard,remove

pop对目标集合中的元素随机删除且无参数

discard删除集合中的某个元素,参数为指定元素,若无该元素,则do nothing

remove删除集合中的某个元素,参数为指定元素,若无该元素,则raise a KeyError

>>> a = {1,2,3,4}
>>> a.pop()
1
>>> a
{2, 3, 4}
>>> a.discard(3)
>>> a
{2, 4}
>>> a.discard(3)
>>> a.remove(2)
>>> a
{4}
>>> a.remove(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 2

union

 将set1和set2的元素排重取合

>>> a = {1,2,3,4}
>>> b= {1,3,5,7}
>>> a.union(b)
{1, 2, 3, 4, 5, 7}

issubset、issuperset

判定set1是否包含(包含于)set2中

>>> set1 = {1,2,3}
>>> set2 = {1,2,3,4,5}
>>> set1.issubset(set2)
True
>>> set1.issuperset(set2)
False
>>> set2.issubset(set1)
False
>>> set2.issuperset(set1)
True
原文地址:https://www.cnblogs.com/fukuda/p/5537153.html