Python循环未获得文件中的所有项目

2024-06-26 00:00:56 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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> %.

有没有办法让打印出来的文件中的每一个名字和每一行数字?提前谢谢!你知道吗


Tags: readlineismain数字infileavgbobscore
2条回答

所以你有5个记录,每个记录有2行。第一个任务是正确地接收这些信息。您可以通过fin.readline()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.

您需要从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) )

相关问题 更多 >