python 数组交、并、差集

1. 数组取交集

aa = [1, 2, 3, 4, 5]
bb = [1, 2, 3, 7, 8]

# 方法一:
intersection  = list(set(a).intersection(set(b)))
print (intersection)
# 方法二
intersection = [val for val in aa if val in bb]
print(intersection )

# 结果输出 [1, 2, 3]

2. 数组取并集

aa = [1, 2, 3, 4, 5]
bb = [1, 2, 3, 7, 8]

# 方法一:
union = list(set(aa).union(set(bb)))
print (union)

# 结果输出 [1, 2, 3, 4, 5, 7, 8]

3. 数组取差集

aa = [1, 2, 3, 4, 5]
bb = [1, 2, 3, 7, 8]

# 方法一:
difference = list(set(bb).difference(set(aa)))  # bb中有而aa中没有的
print (difference)

# 结果输出 [7, 8]

猜你喜欢

转载自blog.csdn.net/u014651560/article/details/110940977