Python2.5 中新增加了集合内容,让我想起了初中数学。
看看:
看看:
>>> b = set()
>>> b.add(1)
>>> b.add(2)
>>> b.add(3)
>>> b.add(4)
>>>
>>> c = set()
>>> c.add(4)
>>> c.add(5)
>>> c.add(6)
>>> d = b.difference(c)
>>> print d
set([1, 2, 3])
>>> print b
set([1, 2, 3, 4])
>>> print c
set([4, 5, 6])
>>> d = b.intersection(c)
>>> print d
set([4])
>>> d = b.union(c)
>>> print d
set([1, 2, 3, 4, 5, 6])
"difference()" 求 b 与 c 不同的部分,"intersection()" 求 b 和 c 的交集,"union()" 求 b 和 c 的并集。
其实集合类型这里还有一个好处,它的值不会重复,就像字典类型的 key 一样。
>>> a = set()
>>> a.add(1)
>>> a.add(2)
>>> a.add(3)
>>> a.add(2)
>>> a.add(1)
>>> print a
set([1, 2, 3])
上面就能看出来了。
用它来排重很好用。