使用yield打印输出

时间:2017-02-08 10:05:32

标签: python yield

这是here的延续。

我使用yield语句而不是return

这是代码:

class Measurements():
    def __init__(self, value, other):
        self.value = value
        self.other = other


class Criteria():
    def __init__(self, new_value, measurements):
        self.new_value = new_value
        self.measurements = measurements

    def method(self):
        for measurement in self.measurements:
            if 20 < measurement.value < 110:
                measurement.value = self.new_value
        return self.measurements

class Evaluate():
    def __init__(self, criteria):
        self.criteria = criteria

    def execute(self):
        for c in self.criteria:
            c.method()
            yield c.measurements


def main():
    criteria = [
        Criteria(999, [Measurements(100, 0.3), Measurements(33, 0.5)]),
        Criteria(999, [Measurements(150, 0.3), Measurements(35, 0.5)]),
    ]

    compare =  [
        Measurements(999, 0.3), Measurements(999, 0.5),
        Measurements(100, 0.3), Measurements(999, 0.5)
    ]

    obs = Evaluate(criteria).execute()

    # here compare

if __name__ == "__main__":
    main()

我想将obs的输出值与compare中的值进行比较。我指的是Measurements部分。

所以,从obs开始,我们(运行代码后的变量值):999,999,150,999(因为如果是

我们来自compare999,999,100,999

2 个答案:

答案 0 :(得分:1)

还有点不确定你想要执行什么检查,但这里有一个例子可以帮助你入门。做了一些改变

# Made compare a list contain lists of Measurements to match criteria
compare =  [
    [Measurements(999, 0.3), Measurements(999, 0.5)],
    [Measurements(100, 0.3), Measurements(999, 0.5)]
]
# Added __repr__ method to Measurement class
def __repr__(self):
    return '{0} {1}'.format(self.value, self.other)

我建议每当你有一个类实例列表时这样做,它会使调试变得更容易,而不是得到它,你会得到更有意义的东西。

<__main__.Measurements object at 0x0000000003E2C438>

现在比较我使用zip的值来将两个列表组合在一起,以便更容易地比较这些值。然后对于内部for循环,我们再次将每个组的嵌套列表压缩在一起。从这里开始,每个项目都是一个测量,我们可以检查它们的值。

for crit_lst, comp_lst in zip(obs, compare):
    for crit_meas, comp_meas in zip(crit_lst, comp_lst):
        print(crit_meas, comp_meas)
        if crit_meas.value != comp_meas.value: # example of comparing their values
            print('Mis-Match', crit_meas.value, comp_meas.value)

答案 1 :(得分:1)

我不知道你是否真的需要测量的二维结构,这会把它变成numpy的三维结构。如果没有必要,可以删除额外的维度。

import numpy as np

lower = 20
upper = 110

meas = np.array([[[100, 0.3], [33, 0.5]], [[150, 0.3], [35, 0.5]]])
crit = np.array([[999, 999]])
comp = np.array([[[100, 0.3], [33, 0.5]], [[150, 0.3], [35, 0.5]]])

mask = (meas[:,:,0] > lower) * (meas[:,:,0] < upper)

meas[mask,0] = (mask * crit)[mask] # apply mask to inner first column

out = (meas == comp).all(axis=2) # compare each measurement to respective one in comp

print(out)

这给出了:

[[False False]
 [ True False]]