python - 类对象的选择性比较

标签 python comparison

我需要对类对象进行多次比较。但是,只有选定字段的值才会进行比较,即:

class Class:
    def __init__(self, value1, value2, value3, dummy_value):
        self.field1 = value1
        self.field2 = value2
        self.field3 = value3
        self.irrelevant_field = dummy_value

obj1 = Class(1, 2, 3, 'a')
obj2 = Class(1, 2, 3, 'b') #compare(obj1, obj2) = True
obj3 = Class(1, 2, 4, 'a') #compare(obj1, obj3) = False

目前我这样做:

def dumm_compare(obj1, obj2):
    if obj1.field1 != obj2.field1:
        return False
    if obj1.field2 != obj2.field2:
        return False
    if obj1.field3 != obj2.field3:
        return False
    return True

由于我的相关字段的实际数量大于 10 个,因此这种方法会导致代码相当庞大。这就是为什么我尝试这样的事情:

def cute_compare(obj1, obj2):
    for field in filter(lambda x: x.startswith('field'), dir(obj1)):
        if getattr(obj1, field) != getattr(obj2, field):
            return False
    return True

代码紧凑;但是,性能会受到很大影响:

import time

starttime = time.time()
for i in range(100000):
    dumm_compare(obj1, obj2)
print('Dumm compare runtime: {:.3f} s'.format(time.time() - starttime))

starttime = time.time()
for i in range(100000):
    cute_compare(obj1, obj2)
print('Cute compare runtime: {:.3f} s'.format(time.time() - start time))

#Dumm compare runtime: 0.046 s
#Cute compare runtime: 1.603 s

有没有办法更有效地实现选择性对象比较?

编辑: 事实上,我需要几个这样的函数(它们通过不同的、有时重叠的字段集来比较对象)。这就是为什么我不想覆盖内置类方法。

最佳答案

如果某个特定比较集中的所有实例都存在这些字段, 尝试保存列表以与类进行比较。

def prepped_compare(obj1, obj2):
    li_field = getattr(obj1, "li_field", None)
    if li_field  is None:
        #grab the list from the compare object, but this assumes a 
        #fixed fieldlist per run.
        #mind you getattr(obj,non-existentfield) blows up anyway
        #so y'all making that assumption already
        li_field = [f for f in vars(obj1) if f.startswith('field')]
        obj1.__class__.li_field = li_field

    for field in li_field:
        if getattr(obj1, field) != getattr(obj2, field):
            return False
    return True    

或者在外部预先计算,更好

def prepped_compare2(obj1, obj2, li_field):

    for field in li_field:
        if getattr(obj1, field) != getattr(obj2, field):
            return False
    return True    


starttime = time.time()
li_field = [f for f in vars(obj1) if f.startswith('field')]
for i in range(100000):
    prepped_compare2(obj1, obj2, li_field)
print('prepped2 compare runtime: {:.3f} s'.format(time.time() - starttime))

输出:

Dumm compare runtime: 0.051 s
Cute compare runtime: 0.762 s
prepped compare runtime: 0.122 s
prepped2 compare runtime: 0.093 s
回复。覆盖eq,我很确定你可以有类似的东西。

def mycomp01(self, obj2) #possibly with a saved field list01 on the class
def mycomp02(self, obj2) #possibly with a saved field list02 on the class

#let's do comp01.
Class.__eq__ = mycomp01
run comp01 tests
Class.__eq__ = mycomp02
run comp02 tests

关于python - 类对象的选择性比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31518198/

相关文章:

python - HTML <li> 有什么限制吗?

c# - C# 中的时间相关着色

sql-server-2008 - 基于数组变量的条件分割

mysql - 高级SQL查询(查询中查询、比较)

C++ - 像git一样获取2个字符串的 "difference"

python - 比较:Pycharm 与 WingIDE

python - 这些查找素数的片段有什么区别?

python - 使用 Pandas 检查 2 个系列中的一对值的最有效方法?

Python:float(2**53+3) 是什么

python - 数据框的 Pandas 合并