使用比较函数查找两个对象列表的交集

品牌文字

tl;博士:

我在 Python 中有两个类对象列表(两者都是相同类型),在比较它们时,我需要通过使用返回TrueFalse.

我需要比较汽车的轮胎以确定轮胎是否匹配(“它会适合”),有时轮胎是否相同(相同品牌/制造商/年份)。

给定下面的示例,我如何将汽车的当前轮胎与find使用该compare.is_exact_match函数从上次调用中返回的潜在轮胎列表进行比较

我看到了这样类似的问题这一个,它可以让我比较基于属性的值对象,但我不知道(怎么)这个同样的方法可以为一个功能比较工作。

详情:

我有一个Car,它的一个属性是一组轮胎(子类Tire):

def Car:
    def __init__(self, ...args):
         self.make = make
         self.model = model
         self.year = year
         self.trim = trim
         self.color = color
         self.vin = vin
         self.tires: [Tire] = tires
         self.potential_matches: [Tire] = []

    def Tire:
        def __init__(self, ...args):
            self.brand = brand
            self.model_number = model_number
            self.year = year
            self.diameter = diameter
            self.width = width
            self.sidewall = sidewall
            self.circumference = self.circumference
            self.revs_per_mile = self.revs_per_mile

我有一些比较复杂的启发式方法,可以比较汽车列表以找到适合这辆车的轮胎。这是一个模拟示例,但让我们假设这是一个轮胎更换市场,以便您了解我们如何去那里。在这种理论产品中,市场上的轮胎数据往往不完整。确定轮胎是否匹配是很昂贵的,所以我们做了一些前期工作来减少这种足迹。一旦我们有了这个,我们通常需要进一步比较轮胎以区分“只是匹配”和“相同的轮胎”。

这看起来像:

@classmethod
def find(cls, car: Car, marketplace_cars: [Car]) -> [Car.Tire]:
    matches = list(filter(lambda c:
         # One thing we can try is comparing the car first. If the car is a match,
         # the tires probably are too.
         car.make == c.make
         and car.model == c.model
         and car.year == c.year
         and car.trim == c.trim

         # If any of those fail, run the expensive heuristic
         and compare.is_match(car, c)
    marketplace_cars))

    # Extract a list of tires from the list of cars that were identified as having matches
    matching_tires = list(itertools.chain(*[m.tires for m in matches]))

    return matching_tires

现在从这个列表中,我们想进一步缩小它以显示任何相同匹配的轮胎这意味着在第一次比较中比较品牌、型号和里程以及所有其他内容。这次compare.is_exact_match获取单个Tire对象并比较它们。

这就是我迷失的地方:

如何将汽车的当前轮胎与find使用该compare.is_exact_match功能从上次调用中返回的潜在轮胎列表进行比较

@classmethod
def find_exact(cls, car: Car) -> [Car.Tire]:

    # Pseudo code, because what do I do here?
    # Should/can I do this with sets, or?
    exact_matches = list(filter(
                          lambda tire, match: compare.is_exact_match(tire, match), 
                          (car.tires, car.potential_matches)))

    # Returns an array of [Car.Tire] that are exact matches
    return exact_matches
品牌文字

事实证明,我真的想得太多了,我只需要一个简单的列表理解。

@classmethod
def find_exact(cls, car: Car) -> [Car.Tire]:

    exact_matches = [m for t in car.tires for m in car.potential_matches if compare.is_exact_match(t, m)]
    """
    for t in car.tires:
        for m in car.potential_matches:
            if compare.is_exact_match(t, m):
                m
    """

    # Returns an array of [Car.Tire] that are exact matches
    return exact_matches

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章