直接上代码,有三种方法,第三种调用库函数效率最高
# ! /usr/bin/env python
# encoding:utf-8
if __name__ == '__main__':
a = [1,2,3,4,5]
b = [2,3,6,7]
u =[]
dif =[]
intersec = []
'''方法一,最简单的方法,容易想到的'''
for item in a:
u.append(item)
if item in b:
intersec.append(item)
if item not in b:
dif.append(item)
for key in b:
u.append(key)
print('u is ',list(set(u))) #u is [1, 2, 3, 4, 5, 6, 7]
print('dif is ', dif) #dif is [1, 4, 5]
print('intersec is ', intersec) #intersec is [2, 3]
'''方法二'''
a = [1,2,3,4,5]
b = [2,3,6,7]
intersec = [item for item in a if item in b]
dif = [item for item in a if item not in b] #不能放在最后,因为b.extend时b已经被改变了
b.extend([i for i in a])
u = b
print('u is ', list(set(u))) # u is [1, 2, 3, 4, 5, 6, 7]
print('dif is ', dif) # dif is [1, 4, 5]
print('intersec is ', intersec) # intersec is [2, 3]
'''方法三,调用库函数,集合操作'''
a = [1,2,3,4,5]
b = [2,3,6,7]
intersec = list(set(a).intersection(set(b)))
u = list(set(a).union(set(b)))
dif = list(set(a).difference(set(b)))
print('u is ', u) # u is [1, 2, 3, 4, 5, 6, 7]
print('dif is ', dif) # dif is [1, 4, 5]
print('intersec is ', intersec) # intersec is [2, 3]