集合的交集并集差集

  1. x = ["a","b","c"]
  2. y = ["a","d","g"]

要求返回两者中没有重复的数据,即:  
  1. ["b","d","c","g"]

此问题的常规解答为:  
  1. result = []
  2. for item in x:
  3.     if item not in y:
  4.         result.append( item ) 
  5. for item in y:
  6.     if item not in x:
  7.         result.append( item )
  8.    
  9. print result # should be ['b', 'c', 'd', 'g']

但显然这种解答与pythonic不沾边!我给出一个使用内置数据结构的解答:  
复制代码
  1. list( (set(x)|set(y)) - (set(x)&set(y)) )

在此基础上,群友“新蟒定安公(292658119)”不断探索,先后给出了一系列的答案:  
复制代码
  1. list( set(x).difference(set(y)).union(set(y).difference(set(x))) ) # 1
  2. list( set(x).symmetric_difference(set(y)) ) # 2
  3. list( set(["a","b","c"])^set(["a","d","g"]) ) # 3

尤其第三个答案,非常pythonic  
其实setpython内置的一种极为方便的高级数据结构,它翻译成中文为“集合”,特点是其元素无重复:  

  1. >>> set( [1,1,2,2] )
  2. set([1, 2])
  3. >>> 

set可以进行如下运算:  


Operation 
Equivalent 
Result 
len(s) 

  

cardinality of set s 

x in s 

  

test x for membership in s 

x not in s 

  

test x for non-membership in s 

s.issubset(t) 

s <= t 

test whether every element in s is in t 

s.issuperset(t) 

s >= t 

test whether every element in t is in s 

s.union(t) 

s | t 

new set with elements from both s and t 

s.intersection(t) 

s & t 

new set with elements common to s and t 

s.difference(t) 

s - t 

new set with elements in s but not in t 

s.symmetric_difference(t) 

s ^ t 

new set with elements in either s or t but not both 

s.copy() 

  

new set with a shallow copy of s 


需要注意的是,从python3.X起,set的初始化与表示方法就有了不同了。在2.X中,set只能通过其他sequence结构初始化,而且表示方法为set( list ) 
复制代码
  1. >>> s = set( ["a","b","c"] )
  2. >>> s
  3. set(['a', 'c', 'b'])
  4. >>> 


而到了3.Xset已经可以直接以元素内容初始化,且表示方法更加准确:  

  1. >>> s = {1,2}
  2. >>> s
  3. {1, 2}
  4. >>> 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值