如何在不使用任何模块或导入的情况下使用python字典创建CSV表



我有一个字典,它从csv文件中获取数据:

def read_results(full_file_path):
csv_dict = {}
with open(full_file_path,'r') as t:
table = t.readlines()[1:]
for line in table:
line = line.replace('n', '')
line = line.split(',')
line = list(map(float, line))
key = (line[1], line[3])
if key in csv_dict:
csv_dict[key].append((line[4], line[5], line[6]))
else:
csv_dict[key] = [(line[4], line[5], line[6])]
return csv_dict

#that looks like this:
{(1.0, 3.0): [(602.0, 1661.0, 0.0), (945.0, 2164.0, 0.0), (141.0, 954.0, 0.0), (138.0, 913.0, 0.0),....}

但现在我需要利用这个字典来创建一个我自己的csv,它需要计算每个值行对其相应键对的平均值,如下所示:

c     b     first     finish     fix/ext 
1     3     744.67     1513.67     0.67 
0.8     3     88     858.67     0.67 
0.8     1.5     301.5     984.5     0.5 
1     1.5     419     844.5     0 

而且我不能使用任何外部库或模块,直到现在我都在尝试:

def Summarize_res(results):
with open('summary_results.csv', 'w', newline='') as f:
header = ['c','b','first','finish','fix/ext']
f.write(str(header))
for line in dict:
first = sum(line[4])/len(line[4])
finish = sum(line[5])/len(line[6])
fix_ext = sum(line[5])/len(line[6])

我不确定这是否正是您想要的,但在这里,对于每个键,它都会找到元组的相应值的平均值,并将其写入文件中。代码肯定可以简化,但我没有太多时间,对不起。

def Summarize_res(dict):
with open('summary_results.csv', 'w') as f:
header = ['c','b','first','finish','fix/ext']
f.write(','.join(str(e) for e in header))
f.write("n")
for key in dict:
key1, key2 = key
first_arr = []
finish_arr = []
fix_arr = []
for element in dict[key]:
first, finish, fix = element
first_arr.append(first)
finish_arr.append(finish)
fix_arr.append(fix)
first_final = sum(first_arr) / len(first_arr)
finish_final = sum(finish_arr) / len(finish_arr) 
fix_final = sum(fix_arr) / len(fix_arr)
result = [key1, key2, first_final, finish_final, fix_final]
f.write(','.join(str(e) for e in result))
f.write("n")
Summarize_res(dict)

这个部分可以直接插入到您以前的代码中,它应该可以工作。

相关内容

最新更新