我一直在尝试创建一个函数,根据它们的值对CSV文件进行排序,然后将输出写入另一个CSV文件。问题是我只是不知道如何根据字典的值对字典进行排序。
以下是输入内容:
mandana,5,7,3,15
jach,3,9,4,20,9,1,8,16,0,5,2,4,7,2,1
sina,19,10,19,6,8,14,3
sarah,0,5,20,14
julie,13,2,5,1,3,10,12,4,13,17,7,7
ally,1,9
sarvin,0,16,16,13,19,2,17,8
预期输出:
ally,5.0
jach,6.066666666666666
mandana,7.5
julie,7.833333333333333
sarah,9.75
sina,11.285714285714286
sarvin,11.375
这是代码:
def calculate_sorted_averages(input_file_name, output_file_name):
with open (input_file_name) as f:
a = []
file1 = csv.reader(f)
file2 = OrderedDict()
for element in list(file1):
file2[element[0]] = [int(j) for j in element[1:]]
for i in file2:
a.append((i + ',' + str(mean(file2[i]))))
with open (output_file_name, 'w', newline='') as o:
file3 = csv.writer(o, delimiter='\n')
file3.writerow(a)
答案 0 :(得分:0)
您可以使用此示例读取数据,将数字转换为整数,计算平均值,将其排序并写回文件:
data = []
with open('input.txt', 'r') as f_in:
for line in f_in:
name, *vals = line.split(',')
data.append([name, sum(map(int, vals)) / len(vals)])
data = sorted(data, key=lambda k: k[1])
with open('output.txt', 'w') as f_out:
for line in data:
print(','.join(map(str, line)), file=f_out)
创建output.txt
:
ally,5.0
jach,6.066666666666666
mandana,7.5
julie,7.833333333333333
sarah,9.75
sina,11.285714285714286
sarvin,11.375