我试图找出我的代码有什么问题。目前,我试图获得具有相同温度的所有物的平均值(ex temp 18 = 225电导率平均值,temp 19 = 15电导率平均值等)。
有人可以告诉我这是一个简单的编码错误还是算法错误并提供一些帮助来解决这个问题?
temp = [18,18,19,19,20]
conductivity = [200,250,20,10,15]
tempcheck = temp[0];
conductivitysum = 0;
datapoint = 0;
assert len(temp) == len(conductivity)
for i in range(len(temp)):
if tempcheck == temp[i]:
datapoint+=1
conductivitysum+=conductivity[i]
else:
print conductivitysum/datapoint
datapoint=0
conductivitysum=0
tempcheck=temp[i]
由于某种原因,它正在打印
225
10
什么时候应该打印出来
225
15
15
答案 0 :(得分:3)
in else子句 把:
conductivitysum=0
datapoint=0
tempcheck = temp[i]
conductivitysum+=conductivity[i]
datapoint+=1
因为当你转到else子句时,你会错过i的特定电导率。它没有得到保存。所以在移动到下一个i之前,请保存电导率
答案 1 :(得分:2)
将else更改为:
for i in range(len(temp)):
if tempcheck == temp[i]:
datapoint+=1
conductivitysum+=conductivity[i]
else:
print conductivitysum/datapoint
datapoint=1
conductivitysum=conductivity[i]
tempcheck=temp[i]
当你到达那对(19,20)时,你需要保留它们并计算一个数据点,而不是0个数据点。目前你正在跳过它们而只保留下一个 - (19,10)。
或者,将其重写为
>>> temp = [18,18,19,19,20]
>>> conductivity = [200,250,20,10,15]
# build a dictionary to group the conductivities by temperature
>>> groups = {}
>>> for (t, c) in zip(temp, conductivity):
... groups[t] = groups.get(t, []) + [c]
...
# view it
>>> groups
{18: [200, 250], 19: [20, 10], 20: [15]}
# average the conductivities for each temperature
>>> for t, cs in groups.items():
print t, float(sum(cs))/len(cs)
...
18 225
19 15
20 15
>>>
答案 2 :(得分:0)
当我看到这段代码时,突然出现的第一件事是zip
函数。我希望以下代码是你想要的。
temp = [18,18,19,19,20]
conductivity = [200,250,20,10,15]
assert len(temp) == len(conductivity)
# Matches each temp value to its corresponding conductivity value with zip
relations = [x for x in zip(temp, conductivity)]
for possible_temp in set(temp): # Takes each possible temparature (18,19,20)
total = 0
divide_by = 0
# The next four lines of code will check each match and figure out the
# summed total conductivity value for each temp value and how much it
# should be divided by to create an average.
for relation in relations:
if relation[0] == possible_temp:
total += relation[1]
divide_by += 1
print(int(total / divide_by))