0

我正在尝试编写一个程序,该程序从列表中读取一系列名称和数字,如下所示:

5
Jim
79 84 82
Bob
32 12 47
Kelly
90 86 93
Courtney
80 99 89
Chad
89 78 91

数字的格式是:

<Assignment score>   <Quiz Score>   <Exam Score>

每个乘数是:

.3 .1 .6

目前我有这个:

def main():
    inFile = open("input.txt","r")

    numVals = int(inFile.readline())
    for i in range(numVals):
        name = inFile.readline()


    numbers = inFile.readline().split()
    for n in range(len(numbers)):
        numbers[n] = float(int(numbers[n]))

    avg = float(numbers[0]* .3 + numbers[1]* .1 + numbers[2]* .6)
    print(name, "'s Score is",avg,"%.")

    inFile.close()

main()

我的输出应该是这样的:

Jim’s score is <avg>.
Bob’s score is <avg>.
Kelly’s score is <avg>.
Courtney’s score is <avg>.
Chad’s score is <avg>.

但相反,我得到了这个:

Kelly
 's Score is <avg> %.

关于如何打印以获取文件中的每个名称和文件中的每一行数字的任何想法?提前致谢!

4

2 回答 2

0

您需要从 readline 的结果中去除尾随的换行符。

也许是这样的:

weights = [.3, .1, .6]
with open ('file2.txt') as f:
    count = int (f.readline ().strip () )
    for i in range (count):
        name = f.readline ().strip ()
        score = sum (w * s for w,s in zip (weights, (int (x) for x in f.readline ().strip ().split () ) ) )
        print ('{}\'s Score is {} %.'.format (name, score) )
于 2013-02-16T02:11:35.287 回答
0

所以你有 5 条记录,每条有 2 行。第一个任务是正确地摄取这些信息。您可以通过fin.readline()或 via获得一条线路,该线路next(fileobject)也适用于 python3.x。

weights = ( 0.3, 0.1, 0.3 )
with open('datafile') as fin: #open file for reading
    n = int(next(fin)) #read the first line and figure out how many people there will be
    for _ in range(n): #Loop over the records, 2 at a time:
        name = next(fin).strip() #read the name, strip off the whitespace.
        grades = [float(x) for x in next(fin).split()] #read the grades, make then floats
        total = sum( w*g for w,g in zip(weights,grades) )
        print name, total

这实际上与您目前所拥有的并没有太大的不同:

def main():
    inFile = open("input.txt","r")

    numVals = int(inFile.readline())
    for i in range(numVals):
        name = inFile.readline() #add a .strip() here
        #grades = [float(x) for x in inFile.readline().strip()]
        #do the rest of the processing for a single person here 
        #since you have all their info.  If you wait, you'll replace
        #the info you currently have with the info for the next person
        #You'll continue to do that until the last person -- meaning
        #that at the end of the day, you'll only have the info for the
        #last person.
于 2013-02-16T02:14:23.407 回答