Python set详解

前言

set是无序的元素的集合,每个元素都没有重复,并且不能被更改。但是set本身是可以被更改的,可以添加或移除元素,也可以进行数学中的集合运算(如并交补差)

集合的相关操作

1.创建set

可以用{ }或者python的内置函数set()创建集合。其中set里的元素可以是不同类型的(integer,float,tuple,string etc.) 但不能有可变元素(list,set或dictionary)作为它的元素。

>>>my_set={1,2,3,1,2}
>>>my_set
{1,2,3}

>>>my_set=set([1,2,3,1,2])
>>>my_set
{1,2,3}

#*******如果要创建空的集合******
>>>a=set()
>>>type(a)
<class 'set'>

>>>a={}  #由结果可知是产生字典类型
>>>type(a)
><class 'dict'>
2.更新set(添加元素)

不能像list一样用下标或切片来访问或改变set。可以使用add()函数添加单个元素,update()函数添加元组,列表,字符串或其他集合。`

>>>a={1,2,3}
>>>a.add(4)
>>>a
{1,2,3,4}
>>>a.update([1,2,3],[4,3],{6,7,3})
>>> a
{1, 2, 3, 4, 6, 7}
3.从set移除特定元素

可以用discard()函数和remove()函数移除特定元素,唯一的区别是当要移除的元素集合中并不存在时,discard(x)保持不变,而remove(x)会报错。也可以用clear()将整集合清除。

4.python中set的集合操作
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}

#union 并 以下三种方法都可以
>>>A|B
{1, 2, 3, 4, 5, 6, 7, 8}
>>>A.union(B)
{1, 2, 3, 4, 5, 6, 7, 8}
>>>B.union(A)
{1, 2, 3, 4, 5, 6, 7, 8}

#intersection 交 也有以下三种方法
>>>A&B
{4,5}
>>> A.intersection(B)
{4, 5}
>>> B.intersection(A)
{4, 5}

#difference 差
>>>A-B
{1,2,3}
>>> A.difference(B)
{1, 2, 3}
>>> B - A
{8, 6, 7}
>>> B.difference(A)
{8, 6, 7}

#symmetric_difference 补 (除去公有的元素
>>>A^B
{1, 2, 3, 6, 7, 8}
>>> A.symmetric_difference(B)
{1, 2, 3, 6, 7, 8}
>>> B.symmetric_difference(A)
{1, 2, 3, 6, 7, 8}

set相关函数

上文中讲述到的函数,在下面就不再赘述,

MethodDescription
copy()Returns a copy of the set
difference_update()Removes all elements of another set from this set
intersection_update()Updates the set with the intersection of itself and another
symmetric_difference_update()Updates a set with the symmetric difference of itself and another

与set相关的内置函数

FunctionDescription
all()Return True if all elements of the set are true (or if the set is empty).
any()Return True if any element of the set is true. If the set is empty, return False.
enumerate()Return an enumerate object. It contains the index and value of all the items of set as a pair
len()Return the length (the number of items) in the set.
max()Return the largest item in the set.
min()Return the smallest item in the set.
sorted()Return a new sorted list from elements in the set(does not sort the set itself).
sum()Retrun the sum of all elements in the set.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值