我是Python的新手,将其作为职业培训的一部分进行学习,但是从一些HTML和C / C ++开始。关于如何使这个细分市场工作的任何建议都很棒!
def compute(tank_data): #in the parenthesis are the variables you want to pass from one def to another
aggregates = {}
list = []
for tank in tank_data: #
sum = 0
max_value = 0
min_value = 1000
#standdev = 0
for reading in tank_data[tank]:
sum = sum + float(reading)
'''max_value = round(max(float(reading)),2)
min_value = round(min(float(reading)),2)'''
if reading >= max_value:
max_value = float(reading)
else:
max_value = max_value
if reading <= min_value:
min_value = float(reading)
else:
min_value = min_value
#standdev
if tank in aggregates:
aggregates[tank]['avg'] = round(sum/len(tank_data[tank]),2) #computing and printing average simutaneously
aggregates[tank]['max'] = round(max_value,2)
aggregates[tank]['min'] = round(min_value,2)
#aggregates[tank]['STDEV'] = round()
else:
aggregates[tank] = {}
aggregates[tank]['avg'] = round(sum/len(tank_data[tank]),2)
aggregates[tank]['max'] = round(max_value,2)
aggregates[tank]['min'] = round(min_value,2)
#aggregates[tank]['STDEV'] = round()
print aggregates
我获得了正确的文档平均值(将其检查为excel),但只有我的前三个最大值是正确的(我在这里运行的是6个),并且所有最小值都返回“1000”。 / p>
当我使用注释掉的部分时:
'''max_value = round(max(float(reading)),2)
min_value = round(min(float(reading)),2)'''
我收到错误'浮动'对象不可迭代。
非常感谢任何帮助。 :)
答案 0 :(得分:0)
你有一个浮动元素,不要调用max
。如果你有一个列表,元组等等浮动你将使用max,那么获得单个数字的最大值是没有意义的:
round(max(map(float,tank_data[tank])),2) # iterable of floats
round(float(reading),2) # single float
使用您自己的代码,因为我想这是一个练习,将all映射到float并使用read变量来检查:
sm = 0
max_value = float("-inf")
min_value = float("inf")
for reading in map(float,tank_data[tank]): # map all to float
sm += reading
reading = round(reading, 2) # single float
if reading > max_value:
max_value = reading
if reading < min_value:
min_value = reading
您不需要使用max_value = round(...
使用if / else块执行逻辑操作。您应该只在检查到目前为止看到的最低/最高值的当前值后更新。
在遮蔽内置函数时,还应避免使用sum和list作为变量名。
答案 1 :(得分:-1)
使用python的内置函数:
def compute(tank_data):
aggregates = {}
list = []
for tank, data in tank_data.iteritems():
numbers = [float(v) for v in data]
total = sum(numbers)
max_value = max(numbers)
min_value = min(numbers)
info = {
'avg': round(total/len(numbers),2)
'max': round(max_value,2),
'min': round(min_value,2),
}
aggregates.set_default(tank, {}).update(info)
print aggregates