Python基础之列表的交差并集

Python基础之列表的交差并集

一.用for循环实现

'''
    用for循环
'''
a = [1, 2, 3, 4, 5]
b = [2, 4, 5, 6, 7]
# 交集
result1 = [r for r in a if r in b]
print('a与b的交集:', result1)

# 差集 在a中但不在b中
result2 = [r for r in a if r not in b]
print('a与b的差集:', result2)

#并集
result3=a
for r in b:
    if r not in result3:
        result3.append(r)
print('a与b的并集:', result3)

运行结果:

a与b的交集: [2, 4, 5]
a与b的差集: [1, 3]
a与b的并集: [1, 2, 3, 4, 5, 6, 7]

二.用set集合实现

'''
    用set实现
'''
a = [1, 2, 3, 4, 5]
b = [2, 4, 5, 6, 7]
# 交集
result1 = list(set(a).intersection(set(b)))
print('a与b的交集:', result1)

# 差集 在a中但不在b中
result2 = list(set(a).difference(set(b)))
print('a与b的差集:', result2)

#并集
result3=list(set(a).union(set(b)))
print('a与b的并集:', result3)

运行结果:

a与b的交集: [2, 4, 5]
a与b的差集: [1, 3]
a与b的并集: [1, 2, 3, 4, 5, 6, 7]
发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章