sets使用示例

sets的简单使用

示例代码如下(setsTest1.py):

#! /usr/bin/env python
#-*- coding:utf-8 -*-

s1 = set([1,2,3])
s2 = set([2,3,4,5,5])
print "s1 :",s1
print "s2 :",s2
print "s1 - s2 :" , s1 - s2 ," or ",s1.difference(s2) # 差集
print "s1 & s2 :" , s1 & s2 ," or ",s1.intersection(s2) # 交集
print "s1 | s2 :" , s1 | s2 ," or ",s1.union(s2) # 并集

运行效果如下:

$ python setsTest1.py
s1 : set([1, 2, 3])
s2 : set([2, 3, 4, 5])
s1 - s2 : set([1])  or  set([1])
s1 & s2 : set([2, 3])  or  set([2, 3])
s1 | s2 : set([1, 2, 3, 4, 5])  or  set([1, 2, 3, 4, 5])

该代码的github地址: https://github.com/mike-zhang/pyExamples/blob/master/dataStructure/sets_examples/setsTest1.py