# -*- coding = utf-8 -*-
# @Time : 2022/6/27 17:20
# @Author : Suage
# @File : my_list_comparator.py
# 对比函数
def list_comparator(lis1: list, lis2: list):
"""
对比两个列表, 并返回差异
:param lis1: 列表1
:param lis2: 列表2
:return: dict Keys:<br>
'equal(bool)':两个列表是否相同<br>
'l1_lacks(list)':列表2中有但列表1中没有<br>
'l2_lacks(list)':列表1中有但列表2中没有
"""
_l1 = list(set(lis1))
_l2 = list(set(lis2))
_l1.sort()
_l2.sort()
_l1_lacks = list()
_l2_lacks = list()
_i = _j = 0
_l1_length = len(_l1)
_l2_length = len(_l2)
while _i < _l1_length and _j < _l2_length:
if _l1[_i] == _l2[_j]: # 相等情况, 双指针后移
_i += 1
_j += 1
elif _l1[_i] > _l2[_j]: # 不相等情况, l2中的元素l1中没有
_l1_lacks.append(_l2[_j])
_j += 1
else: # 不相等情况, l1中的元素l2中没有
_l2_lacks.append(_l1[_i])
_i += 1
if _i < _l1_length: # 当对比结束, l1剩余元素即为l2缺少元素
for _index in range(_i, _l1_length): # 循环添加至l1_lacks
_l2_lacks.append(_l1[_index])
if _j < _l2_length: # 当对比结束, l2剩余元素即为l1缺少元素
for _index in range(_j, _l2_length): # 循环添加至l2_lacks
_l1_lacks.append(_l2[_index])
return {
'equal': not (_l1_lacks or _l2_lacks),
'l1_lacks': _l1_lacks,
'l2_lacks': _l2_lacks,
}
# 测试代码
from random import randint
from time import time
min_range = 5
max_range = 10
quantity = lambda: randint(min_range, max_range)
num = lambda: randint(-max_range, max_range)
print('排序前:')
l1 = list(num() for _ in range(quantity()))
print(l1)
l2 = list(num() for _ in range(quantity()))
print(l2)
print('开始对比')
st = time()
my_res = list_comparator(l1, l2)
cost = time() - st
print('对比结束')
l1.sort()
l2.sort()
print('排序后:')
print(l1)
print(l2)
print('对比结果:')
print(my_res)
print(f"Cost time: {cost:.2f}s")
测试代码运行结果:
排序前:
[6, -10, -10, 5, -8]
[-8, -2, 8, -6, 3, -8, 8]
开始对比
对比结束
排序后:
[-10, -10, -8, 5, 6]
[-8, -8, -6, -2, 3, 8, 8]
对比结果:
{‘equal’: False, ‘l1_lacks’: [-6, -2, 3, 8], ‘l2_lacks’: [-10, 5, 6]}
Cost time: 0.00s