我有一个csv文件,其中包含名称和均值列表。 例如:
ali,5.0
hamid,6.066666666666666
mandana,7.5
soheila,7.833333333333333
sara,9.75
sina,11.285714285714286
sarvin,11.375
我将用三个较低的平均值重写csv。我已经编写了代码,但是再次写入csv时遇到了问题。我应该保持均值作为输入。
import csv
import itertools
from collections import OrderedDict
with open ('grades4.csv', 'r') as input_file:
reader=csv.reader(input_file)
val1=[]
key=list()
threelowval=[]
for row in reader:
k = row[0]
val=[num for num in row[1:]] #seperate a number in every row
key.append(k) #making a name -key- list
val1.append(val) #making a value list
value = list(itertools.chain.from_iterable(val1)) #making a simple list from list of list in value
value=[float(i) for i in value] ##changing string to float in values
#print(key)
#print(value)
dictionary = dict(zip(key, value))
#print(dictionary)
findic=OrderedDict(sorted(dictionary.items(), key=lambda t: t[1])) ##making a sorted list by OrderedDict
#print(findic)
##make a separation for the final dict to derive the three lower mean
lv=[]
for item in findic.values():
lv.append(item)
#print(lv)
for item in lv[0:3]:
threelowval.append(item)
print(threelowval)
我尝试了下面的代码,但出现错误。
with open('grades4.csv', 'w', newline='') as output_file_name:
writer = csv.writer(output_file_name)
writer.writerows(threelowval)
预期结果:
5.0
6.066666666666666
7.5
答案 0 :(得分:0)
您应该尝试以下操作:
with open('grades4.csv', 'w', newline='') as output_file_name:
writer = csv.writer(output_file_name)
for i in threelowval:
writer.writerow([i])
答案 1 :(得分:0)
我尝试使用下面的代码并收到正确的结果。
with open('grades4.csv', 'w', newline='') as output_file_name:
writer = csv.writer(output_file_name)
writer.writerows(map(lambda x: [x], threelowval))