【问题标题】:Test if all objects have same member value测试所有对象是否具有相同的成员值
【发布时间】:2017-08-30 00:20:19
【问题描述】:

我在 有一个简单的类:

class simple(object):
    def __init__(self, theType, someNum):
        self.theType = theType
        self.someNum = someNum

稍后在我的程序中,我创建了这个类的多个实例化,即:

a = simple('A', 1)
b = simple('A', 2)
c = simple('B', 3)
d = simple('B', 4)
e = simple('C', 5)

allThings = [a, b, c, d, e] # Fails "areAllOfSameType(allThings)" check

a = simple('B', 1)
b = simple('B', 2)
c = simple('B', 3)
d = simple('B', 4)
e = simple('B', 5)

allThings = [a, b, c, d, e] # Passes "areAllOfSameType(allThings)" check

我需要测试allThings 中的所有元素是否具有相同的simple.theType 值。我将如何为此编写通用测试,以便将来可以包含新的“类型”(即DEF 等)而不必重新编写我的测试逻辑?我可以想出一种通过直方图来做到这一点的方法,但我认为有一种“pythonic”方法可以做到这一点。

【问题讨论】:

    标签: python python linux unique membership


    【解决方案1】:

    只需使用all() 函数将每个对象与第一项的类型进行比较:

    all(obj.theType == allThings[0].theType for obj in allThings)
    

    如果列表为空,也不会有IndexError

    all() 短路,因此如果一个对象与另一个对象的类型不同,则循环立即中断并返回False

    【讨论】:

      【解决方案2】:

      您可以使用itertools recipe for this: all_equal(逐字复制):

      from itertools import groupby
      
      def all_equal(iterable):
          "Returns True if all the elements are equal to each other"
          g = groupby(iterable)
          return next(g, True) and not next(g, False)
      

      然后您可以使用访问theType 属性的生成器表达式调用它:

      >>> allThings = [simple('B', 1), simple('B', 2), simple('B', 3), simple('B', 4), simple('B', 5)]
      >>> all_equal(inst.theType for inst in allThings)
      True
      
      >>> allThings = [simple('A', 1), simple('B', 2), simple('B', 3), simple('B', 4), simple('B', 5)]
      >>> all_equal(inst.theType for inst in allThings)
      False
      

      鉴于它实际上是作为解决方案放入 Python 文档中的,似乎它可能是解决此类问题的最佳(或至少推荐)方法之一。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-09
        • 1970-01-01
        • 1970-01-01
        • 2023-03-12
        • 2022-01-20
        • 1970-01-01
        • 2021-12-18
        • 1970-01-01
        相关资源
        最近更新 更多