我试图计算这个测量的最后一个数的平均值(那些属于同一批/第一个数字)。
1, 73
1, 101
2, 17
2, 23例如,我希望我的代码返回上述值的2个平均值(期望的输出):
1 87.0. #(73+101)/2
2 20.0 #(17+23)/2但是不知怎么的,我的代码只返回了一个值,找不到问题,如果有人能告诉我问题是什么,我会很感激的!这是我的密码!
def collect_exp_data(file_name):
data = dict()
with open(file_name, 'r') as h:
for line in h:
batch, x, y, value = line.split(',')
print(batch)
if not batch in data:
data[batch] = []
data[batch] += [(float(x),float(y),float(value))]
return data
def value_average(dict):
for batch, sample in dict.items():
average_list_length = 0
average_list_sum = 0
for x,y,value in sample:
if x**2 + y**2 <= 1:
average_list_sum += value
average_list_length += 1
average = average_list_sum/average_list_length
return batch, average
for batch, sample in collect_exp_data("/Users/../Desktop/sample1.txt").items():
print(value_average(collect_exp_data("/Users/../Desktop/sample1.txt")))这就是我要回来的
('1', 87.0)发布于 2022-09-20 10:45:47
您似乎两次运行主循环,第一次在for batch, sample in collect_exp_data(...文件的末尾运行,第二次在value_average函数中运行。只需要其中一项。下面是一个经过修改的示例,它生成一个包含所请求的值的字典:
def value_average(data):
return_dict = {}
for batch, sample in data.items():
average_list_length = 0
average_list_sum = 0
for x, y, value in sample:
if x**2 + y**2 <= 1:
average_list_sum += value
average_list_length += 1
average = average_list_sum/average_list_length
return_dict[batch] = average
return return_dict
print(value_average(collect_exp_data("/Users/../Desktop/sample1.txt")))另外,不要将dict、list或其他内置的python类型作为变量名使用,这很可能会在以后搞砸一些代码,这是一种糟糕的做法。
https://stackoverflow.com/questions/73785149
复制相似问题