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))
python集合操作,比较两个列表元素的差异
最新推荐文章于 2024-05-06 16:59:08 发布
本文介绍了使用Python的`@timing_decorator`装饰器测量`set_operations`和`set_operations2`函数执行时间,这两个函数分别实现并集、交集和差集操作,并将结果转换为DataFrame。通过随机生成大样本数据,展示性能分析结果。
摘要由CSDN通过智能技术生成