python取交集、并集、差集

本文详细介绍了如何使用Python进行集合操作,包括交集、并集和差集的计算方法。此外,还提供了处理多个数组求交集的递归函数实现,为Python编程爱好者提供实用的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过python取交集

    intersection = [i for i in a if i in b]
    intersection = list(set(a).intersection(set(b)))

取并集

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

取差集

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

对于多个数组求交集:

def fm(x, y):
    return list(set(x).intersection(set(y))) if isinstance(x, list) and isinstance(y, list) else 'error'


def fn(x):
    return x[0] if len(x) == 1 else [] if len(x) == 0 else reduce(fm, tuple(y for y in x))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值