我有点麻烦。因此,对于我的任务,我的老师希望我们读入数据并将数据输出到另一个文件中。现在,我们正在阅读的数据是学生姓名(第一行)和他们的成绩(第2行)。现在,他希望我们读取它们,然后将它们写入另一个文件。把它们写成两行。第一行是学生的名字,第二行是平均值。然后,将平均值写入列表,并通过均值,中位数和标准差运行整个列表。以下是该文件中某些数据的示例。
Aiello,Joseph
88 75 80
Alexander,Charles
90 93 100 98
Cambell,Heather
100 100
Denniston,Nelson
56 70 65
所以,如你所见,它的姓氏首先用逗号分隔,然后是第一个。然后,在第二行,他们的成绩。他希望我们找到他们的平均值,然后在学生名下写下。这就是我遇到麻烦的部分。我知道如何找到平均值。添加成绩,然后除以他们获得的成绩数。但是如何将它放入python?有人可以帮忙吗?此外,我已经有一个平均值,中位数,标准偏差程序。我如何将从第一部分得到的平均值放入列表,然后将整个列表放入均值,中位数,标准偏差程序。回到我原来的问题。到目前为止我有什么问题吗?我需要添加/更改的任何内容?这是我的代码。
def main():
input1 = open('StudentGrades.dat', 'r')
output = open('StudentsAvg', 'w')
for nextLine in input1:
output.write(nextLine)
list1 = nextLine.split()
count = int(list1[3])
for p in range(count):
nextLine = input1.readlin()
output.write(nextLine)
list2 = nextLine.split()
name = int(list2[1])
grades = list2[2]
pos = grades.index(grade)
avg =
答案 0 :(得分:0)
对原始代码进行了一些改进:
def averagMarksCalculator(): # Learn to name your functions "Meaningfully"
# Using with clause - Learn to love it as much as you can!
with open('StudentGrades.dat') as input1, open('StudentsAvg.txt', 'w') as output:
for nextLine in input1:
strToWrite = nextLine; # Write student's name
output.write(nextLine) # Print student name
list1 = (input1.readline()).split() # split them into individual strings
avg = 0 # initialise
list1 = [int(x) for x in list1]
avg = sum(list1)/len(list1)
output.write("Average marks........"+str(avg)+"\r\n") # avg marks of student
input1.close()
output.close()
请注意" \ r \ n"是在学生的姓名和结果文件上打印的平均分数后确保你有一个行间隔。如果您不需要将空的新行作为分隔符,请使用" \ r"仅
答案 1 :(得分:0)
这里似乎有一些问题。首先,你从文件中读取的所有内容都是字符串,而不是数字。其次,您应该在相同的for循环中执行所有这些操作,其中您读取了行。 (还有一点 - 使用with
语句允许文件对象在完成后自动销毁。)因此,您可以按如下方式修改代码:
def main():
with open('StudentGrades.dat', 'r') as input1, open('StudentsAvg.txt', 'w') as output:
counter = 0
student_name = ''
for nextLine in input1:
if counter % 2 == 0:
student_name = nextLine
else:
grades = [int(x) for x in nextLine.split()]
avg = sum(grades) / len(grades)
print(student_name, file=output)
print(str(avg), file=output)
counter += 1
请注意,print(str, file)
是写入文件的当前首选方法。