python 集合set remove update add

1.

集合(set):把不同的元素组成一起形成集合,是python基本的数据类型。

集合对象是一组无序排列hashable value:集合成员可以做字典的键。

集合就像是 list 和 dict 的组合。

#coding:utf8

a=['h','e','l','l','o']

a=set(a)
b=set('welcome')

print " a = " ,a
print " b = " ,b
print " 并集 ",a.union(b)  #a|b  #并集
print " 并集 ",a|b  #并集
print '*'*30
print " 交集 ",a.intersection(b) #交集
print " 交集 ",a&b  #交集
print '*'*30
print " 差集 ",b-a  #差集
print " 差集 ",b.difference(a)   #差集
print " 差集 ",a-b
print '*'*30
print " 对称差集 ",a^b  #对称差集
print " 对称差集 ",a.symmetric_difference(b)  #对称差集
'''
 a =  set(['h', 'e', 'l', 'o'])
 b =  set(['c', 'e', 'm', 'l', 'o', 'w'])
 并集  set(['c', 'e', 'h', 'm', 'l', 'o', 'w'])
 并集  set(['c', 'e', 'h', 'm', 'l', 'o', 'w'])
******************************
 交集  set(['e', 'l', 'o'])
 交集  set(['e', 'l', 'o'])
******************************
 差集  set(['c', 'm', 'w'])
 差集  set(['c', 'm', 'w'])
 差集  set(['h'])
******************************
 对称差集  set(['c', 'w', 'h', 'm'])
 对称差集  set(['c', 'w', 'h', 'm'])
'''

 2.添加 删除 set

#coding:utf8

a=set('hello')
print a

a=set('hello')
a.update("asdf")

print 'a.update("asdf") ',a

a=set('hello')
a.add("asdf")

print 'a.add("asdf") ',a

a.pop()  #随机删除了一个
print a

a.discard('p')#当集合中没有这个元素的时候,不会报错
a.remove('t') #当集合中没有这个元素的时候报错
'''
set(['h', 'e', 'l', 'o'])
a.update("asdf")  set(['a', 'e', 'd', 'f', 'h', 'l', 'o', 's'])
a.add("asdf")  set(['h', 'asdf', 'e', 'l', 'o'])
set(['asdf', 'e', 'l', 'o'])
    a.remove('t') #当集合中没有这个元素的时候报错
Traceback (most recent call last):
  File "D:\AlamTW\study\python\20170711.py", line 20, in <module>
KeyError: 't'
'''

  

  

转载于:https://www.cnblogs.com/alamZ/p/7152948.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值