python列表的交、并、差集(Intersection, union and difference sets of Python lists)

#!/usr/bin/env python3

l1 = [‘1′,’2′,’3′,’4’]l2 = [‘3′,’4′,’5′,’6’]# 交集result1 = [i for i in l1 if i in l2]result2 = list(set(l1).intersection(set(l2)))print(result1)print(result2)

# 并集result3 = list(set(l1).union(set(l2)))print(result3)

# 差集# 元素在 l1 不在 l2result4 = list(set(l1).difference(set(l2)))print(result4)

————————

#!/usr/bin/env python3

l1 = [‘1′,’2′,’3′,’4’]l2 = [‘3′,’4′,’5′,’6’]# 交集result1 = [i for i in l1 if i in l2]result2 = list(set(l1).intersection(set(l2)))print(result1)print(result2)

# 并集result3 = list(set(l1).union(set(l2)))print(result3)

# 差集# 元素在 l1 不在 l2result4 = list(set(l1).difference(set(l2)))print(result4)