python获得两个数组交集、并集、差集的方法

1.交集

# 方法一:
a = [2, 3, 4, 5]
b = [2, 5, 8]
tmp = [val for val in a if val in b]
print(tmp)
# [2, 5]

# 方法二
print (list(set(a).intersection(set(b))))

2. 并集

print (list(set(a).union(set(b))))

3.差集

print (list(set(b).difference(set(a)))) # b中有而a中没有的

 

http://www.waitingfy.com/archives/3927

3927

Leave a Reply

Name and Email Address are required fields.
Your email will not be published or shared with third parties.