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

つまり、それぞれ2行の5つのレコードがあります。最初のタスクは、その情報を適切に取り込むことです。python3.xでも動作する経由fin.readline()または経由で行を取得できます。next(fileobject)

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 に答える