python集合操作,比较两个列表元素的差异

本文介绍了使用Python的`@timing_decorator`装饰器测量`set_operations`和`set_operations2`函数执行时间,这两个函数分别实现并集、交集和差集操作,并将结果转换为DataFrame。通过随机生成大样本数据,展示性能分析结果。
摘要由CSDN通过智能技术生成
import pandas as pd
import time
def timing_decorator(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"Function {func.__name__} took {end_time - start_time} seconds to run.")
        return result
    return wrapper

# 交、并、差
@timing_decorator
def set_operations(set_a, set_b):
    # 求并集
    union = set_a.union(set_b)
    # 判断是否属于集合A
    in_a = [x in set_a for x in union]
    # 判断是否属于集合B
    in_b = [x in set_b for x in union]
    # 判断是否属于集合A和集合B的交集
    in_union = [(x in set_a) and (x in set_b) for x in union]
    # 判断是否属于集合A且不属于集合B
    in_a_not_b = [(x in set_a) and (x not in set_b) for x in union]
    # 判断是否属于集合B且不属于集合A
    in_b_not_a = [(x in set_b) and (x not in set_a) for x in union]
    # 构造输出DataFrame
    df = pd.DataFrame({'Element': list(union),
                       'In Set A': in_a,
                       'In Set B': in_b,
                       'In intersection': in_union,
                       'In A not B': in_a_not_b,
                       'In B not A': in_b_not_a})
    return df

@timing_decorator
def set_operations2(set_a, set_b):
    # 求交集
    intersection = set_a.intersection(set_b)
    # 求并集
    union = set_a.union(set_b)
    # 求差集
    set_a_not_b = set_a.difference(set_b)
    set_b_not_a = set_b.difference(set_a)

    # 构造输出DataFrame
    df = pd.DataFrame({'Element': list(union),
                       'In Set A': [x in set_a for x in union],
                       'In Set B': [x in set_b for x in union],
                       'In intersection': [x in intersection for x in union],
                       'In A not B': [x in set_a_not_b for x in union],
                       'In B not A': [x in set_b_not_a for x in union]})
    return df


import random
numbers = range(0,100000000,1)
la = random.sample(numbers, 1000000)
lb = random.sample(numbers, 1000000)
print(len(la),len(lb))
set_operations(set(la), set(lb))
set_operations2(set(la), set(lb))

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值