我有一个测量列表,如:
[[Measurements(100, 0.3)],
[Measurements(33, 0.5)]]
然后,我有一个列表,其中包含一些包含测量列表的标准:
[Criteria(999, [[Measurements(100, 0.3)],
[Measurements(33, 0.5)]])],
[Criteria(999, [[Measurements(150, 0.3)],
[Measurements(35, 0.5)]])]
最后,我想提供上面的列表作为输入并执行代码:
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):
# Here, I am iterating through all measurements
# and replace the value according to criteria
for idx, x in enumerate(self.measurements):
if (self.measurements[idx].value > 20 and
self.measurements[idx].value < 110):
self.measurements[idx].value = self.new_value
return self.measurements
class Evaluate():
def __init__(self, criteria):
self.criteria = criteria
def execute(self):
criteria = self.criteria
# Here, I am iterating through all criteria
# and call the method from criteria
for i, c in enumerate(criteria):
c.method()
return 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)]])]
]
obs = (Evaluate(criteria).execute())
if __name__ == "__main__":
main()
我正在接收c.method()
AttributeError: 'list' object has no attribute 'method'
我希望我的结果成为新修正的测量值,所以:
[[Measurements(999, 0.3)],
[Measurements(999, 0.5)]],
[Measurements(150, 0.3)],
[Measurements(999, 0.5)]]
答案 0 :(得分:2)
您的所有Criteria()
和Measurement()
对象都存储在单元素列表中,而单元素列表又存储在更大的列表中。要么考虑到这一点,要么不使用单元素嵌套列表。
我没有看到这些单元素列表的任何原因;以下定义应该使您的代码有效:
criteria = [
Criteria(999, [Measurements(100, 0.3), Measurements(33, 0.5)]),
Criteria(999, [Measurements(150, 0.3), Measurements(35, 0.5)]),
]
否则你将不得不每次都提取一个元素,或者使用嵌套循环:
def execute(self):
for c in self.criteria:
c[0].method()
或
def execute(self):
for c_list in self.criteria:
for c in c_list:
c.method()
您还应该不在return
循环中使用for
,至少在您想要获得所有条件的衡量标准时。在列表中收集测量值,然后返回该列表。
您在self
循环中也使用Criteria.method()
方式太多次了。不需要enumerate()
,您不需要索引来改变可变对象。
更正后的代码:
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):
results = []
for c in self.criteria:
measurements = c.method()
results.extend(measurements)
return results
def main():
criteria = [
Criteria(999, [Measurements(100, 0.3), Measurements(33, 0.5)]),
Criteria(999, [Measurements(150, 0.3), Measurements(35, 0.5)]),
]
obs = Evaluate(criteria).execute()