gpt4 book ai didi

python - 高效循环和比较两个相似对象的属性

转载 作者:行者123 更新时间:2023-12-02 18:19:20 27 4
gpt4 key购买 nike

我有一个函数find(),它需要循环遍历许多对象,通过比较一堆属性来识别相似的对象。

class Target:

def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c

class Source:

def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c


def find(target: Target, source_set: set):
for s in source_set:
if s.a == target.a:
if s.b == target.b:
if s.c == target.c:
print("Found!")


source_set = {
Source(a=1, b=2, c=3),
Source(a=4, b=2, c=4)
}

target = Target(a=4, b=2, c=4)

find(target, source_set)

当前函数非常慢,因为我的 source_set 可能有数百万个。

source_set 创建及其 Source 对象可以调整(例如类型)。 source_set 本身在初始化后不会被修改。

Source 对象创建的输入来自具有相同属性的字典。一个 Source 的原始输入数据如下所示:

{'a': '1', 'b': '2', 'c': '3'}

使用多个目标搜索 source_set。

有没有一种提高效率的好方法?我希望不需要更改数据结构。

最佳答案

无需任何外部库,即可修改各个类的__hash__方法

class Target:

...

def __hash__(self):
return hash(frozenset(self.__dict__.items()))


class Source:

...

def __hash__(self):
return hash(frozenset(self.__dict__.items()))

现在尝试:

count = len({hash(target),}.intersection(map(hash, source_set)))
print(count)

# Output
1

关于python - 高效循环和比较两个相似对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71086669/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com