我知道它已经被问到但是答案超级不清楚了
第一个要求是打开一个文件(遗憾的是我不知道该怎么做)
第二个要求是执行以下操作的代码段:
每一行代表一名学生,由学生编号,姓名,部门代码和期中成绩组成,所有这些都以空白
分隔所以我认为我不能将该元素作为目标,因为它被空格分开了?
以下是该文件的摘录,显示了行结构
987654322 Xu Carolyn L0101 19.5
233432555 Jones Billy Andrew L5101 16.0
555432345 Patel Amrit L0101 13.5
888332441 Fletcher Bobby L0201 18
777998713 Van Ryan Sarah Jane L5101 20
877633234 Zhang Peter L0102 9.5
543444555 Martin Joseph L0101 15
876543222 Abdolhosseini Mohammad Mazen L0102 18.5
我收到了以下提示:
rstrip()
删除行尾的无关空格。我不明白第二个提示。
这是我到目前为止所做的:
counter = 0
elements = -1
for sets in the_file
elements = elements + 1
if elements = 3
我知道它与readlines()
有关,并且定位了部分代码。
答案 0 :(得分:1)
marks = [float(line.strip().split()[-1]) for line in open('path/to/input/file')]
average = sum(marks)/len(marks)
希望这有帮助
答案 1 :(得分:0)
Open and writing to files strip method
这样的东西?
data = {}
with open(filename) as f:#open a file
for line in f.readlines():#proceed through file lines
#next row is to split data using spaces and them skip empty using strip
stData = [x.strip() for x in line.split() if x.strip()]
#assign to variables
studentN, studentName, sectionCode, midtermGrade = stData
if sectionCode not in data:
data[sectionCode] = []
#building dict, key is a section code, value is a tuple with student info
data[sectionCode].append([studentN, studentName, float(midtermGrade)]
#make calculations
for k,v in data.iteritems():#iteritems returns you (key, value) pair on each iteration
print 'Section:' + k + ' Grade:' + str(sum(x[2] for x in v['grade']))
答案 2 :(得分:0)
或多或少:
infile = open('grade_file.txt', 'r')
score = 0
n = 0
for line in infile.readlines():
score += float(line.rstrip().split()[-1])
n += 1
avg = score / n