python中求列表的交集和并集
1、
>>> a = ["aaa","bbb","ccc","ddd"]
>>> b = ["ccc","ddd","eee","fff"]
>>> c = a + b
>>> c
['aaa', 'bbb', 'ccc', 'ddd', 'ccc', 'ddd', 'eee', 'fff']
>>> d = []
>>> for i in c:
if c.count(i) >= 2:
d.append(i)
>>> d
['ccc', 'ddd', 'ccc', 'ddd']
>>> d = list(set(d))
>>> d ## 交集
['ccc', 'ddd']
>>> e = list(set(c))
>>> e ## 并集
['ccc', 'fff', 'bbb', 'eee', 'aaa', 'ddd']
2、
>>> a = ["aaa","bbb","ccc","ddd"]
>>> b = ["ccc","ddd","eee","fff"]
>>> c = []
>>> for i in a:
if i in b:
c.append(i)
>>> c
['ccc', 'ddd']
>>> c = list(set(c))
>>> c ##交集
['ccc', 'ddd']
>>> d = []
>>> for i in a:
if i not in b:
d.append(i)
>>> d
['aaa', 'bbb']
>>> e = d + b
>>> e
['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff']
>>> e = list(set(e))
>>> e ## 并集
['ccc', 'aaa', 'eee', 'ddd', 'fff', 'bbb']