python set() 函数 解析(交集,差集,并集)
set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。
set 语法:
class set([iterable])
参数说明:
- iterable -- 可迭代对象对象;
返回值 : 返回新的集合对象。
实例:
>>>x = set('catroom')
>>> y = set('google')
>>> x, y
(set(['c', 'a', 't', 'r', 'o','m']), set(['e', 'o', 'g', 'l'])) # 重复的被删除
>>> x & y # 交集
set(['o'])
>>> x | y # 并集
set(['c','a','t','m','b', 'e', 'g', 'l', 'o', 'n', 'r', 'u'])
>>> x - y # 差集
set(['r', 'c', 'a', 't','m'])
>>>