Python set (2)

python的set和其他语言类似, 是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素. 集合对象还支持union(联合), intersection(交), difference(差)和sysmmetric difference(对称差集)等数学运算.

s={1,2,"a"}
 type(s)
set

x=set("python")
x

{'h', 'n', 'o', 'p', 't', 'y'}

y=set(["y","a",1])
y
{1, 'a', 'y'}


#去重

a=[1,1,2,2,3,3]
b=set(a)
b

{1, 2, 3}


y.add(2)
y.add("hello")

{1, 2, 'a', 'hello', 'y'}

#从 set “s”中删除元素 , 如果不存在则引发 KeyError
y.remove("hello")
y.remove(2)

{1, 'a', 'y'}

#如果在 set “s”中存在元素 x, 则删除
y.discard(1)

#删除并且返回 set “y”中的一个不确定的元素, 如果为空则引发 KeyError

y.pop()

#删除 set “y”中的所有元素并保留set
y.clear()

y
set()


y.update([3,4,5])

 {1, 3, 4, 5, 'a', 'y'}

len(y)

"x" in y

False

#测试是否 s 中的每一个元素都在 t 中

x=y


#测试是否 y 中的每一个元素都在 x 中,即 x包含y

x=y

y.issubset(x)

y<=x

#测试是否 x 中的每一个元素都在 y中,即y包含x

y.issuperset(x)

y>=x

#返回一个新的 set 包含 x 和 y 中的每一个元素

x=set("python1")

y.union(x)

x|y

#返回一个新的 set 包含 x 和 y 中的公共元素

y.intersection(x)

x&y

#返回一个新的 set 包含 y 中有但是 x 中没有的元素

y.difference(x)

y-x

#返回一个新的 set 包含 x 和 y 中不重复的元素

y.symmetric_difference(x)

y^x


#set y的一个浅复制
z=y.copy()

dir(set)
['__and__',
 '__class__',
 '__cmp__',
 '__contains__',
 '__delattr__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__iand__',
 '__init__',
 '__ior__',
 '__isub__',
 '__iter__',
 '__ixor__',
 '__le__',
 '__len__',
 '__lt__',
 '__ne__',
 '__new__',
 '__or__',
 '__rand__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__ror__',
 '__rsub__',
 '__rxor__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__sub__',
 '__subclasshook__',
 '__xor__',
 'add',
 'clear',
 'copy',
 'difference',
 'difference_update',
 'discard',
 'intersection',
 'intersection_update',
 'isdisjoint',
 'issubset',
 'issuperset',
 'pop',
 'remove',
 'symmetric_difference',
 'symmetric_difference_update',
 'union',
 'update']
 
 help(set.add)
 Help on method_descriptor:
 add(...)
     Add an element to a set.
     This has no effect if the element is already present.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值