2016-08-07 4 views
0
import operator 

with open("D://program.txt") as f: 
Results = {} 
for line in f: 
    part_one,part_two = line.split() 
    Results[part_one] = part_two 


c=sum(int(Results[x]) for x in Results) 
r=c/12 
d=len(Results) 
F=max(Results.items(), key=operator.itemgetter(1))[0] 
u=min(Results.items(), key=operator.itemgetter(1))[0] 
print ("Number of entries are",d) 
print ("Student with HIGHEST mark is",F) 
print ("Student with LOWEST mark is",u) 
print ("Avarage mark is",r) 
Results = [ (v,k) for k,v in Results.items() ] 
Results.sort(reverse=True) 
for v,k in Results: 
print(k,v) 

import sys 

orig_stdout = sys.stdout 
f = open('D://programssr.txt', 'w') 
sys.stdout = f 
print ('Number of entries are',d) 
print ("Student with HIGHEST mark is",F) 
print ("Student with LOWEST mark is",u) 
print ("Avarage mark is",r) 
for v,k in Results: 
print(k,v) 

sys.stdout = orig_stdout 
f.close() 

나는 txt 파일을 읽길 원하지만 문제는 파일에서 이름과 기호 때문에 파일을 쓰고 싶은 결과를 계산할 수 없다는 것입니다. 그것은 전체를 반복하기 전에 내가 잘못이사전에서 파이썬으로 계산하는 방법

NAMES MARKS 
Lux  95 
Veron 70 
Lesley 88 
Sticks 80 
Tipsey 40 
Joe  62 
Goms 18 
Wesley 35 
Villa 11 
Dentist 72 
Onty 50 

답변

0

그냥 next() 기능을 사용하여 첫 번째 줄을 소비 뭐하는 거지 TXT의 file..Help에있는 이름 마크를 제거하지 않고 계산을 할 괜찮아요 작동합니다

with open("D://program.txt") as f: 
    Results = {} 
    next(f) 
    for line in f: 
     part_one,part_two = line.split() 
     Results[part_one] = part_two 

파일 객체는 반복자와 같은 객체 (반복 가능한 원 샷)이므로 반복 할 때 항목을 소비하므로 더 이상 해당 객체에 액세스 할 수 없습니다.

관련 문제