2015-01-29 3 views
-1

나는이의 형식으로 파이썬 사전에 텍스트 파일에서 시험 성적의 결과를 추가하는 코드의 비트 만든 :사전에 키에 지정된 값의 평균을 찾는 방법은 무엇입니까?

{'Ruan': '22', 'hello': [22, 1], 'kurun': '29'} 

을 그리고 난 모든 사람의 점수의 평균을 작업 할이

student_average = sum((diction1[name]))/len((diction1[name])) 
TypeError: unsupported operand type(s) for +: 'int' and 'str' 

내가 너트이 완전히 무엇을 의미하는지 이해 않고, 그나마 해결하는 방법을 알고 :이 오류가

while choice == 'av': 
    if schClass == '1': 
    schClass = open("scores1.txt", 'r') 
    li = open("scores1.txt", 'r') 
    data = li.read().splitlines() 
    for li in data: 
     name = li.split(":")[0] 
     score = li.split(":")[1] 
     if name not in diction1: 
      diction1[name] = score 
     if name in diction1: 
        diction1[name] = [int(diction1[name]),int(score)]  
     print(diction1) 
     averages_dct = {} 
     for name in diction1: 
      student_average = sum((diction1[name]))/len((diction1[name])) 
      averages_dct.update({name: student_average}) 
     reversed_dct = {averages_dct[k]: [] for k in averages_dct} 
     for average in reversed_dct: 
      for name in averages_dct: 
       if average == averages_dct[name]: 
          reversed_dct[average].append(name) 
          for av in sorted(reversed_dct, reverse=True): 
           print('average: %s, students: %s' % (av, reversed_dct[av])) 

: 내가 지금까지 시도한 것입니다 그거야?

+0

당신이 (내가 의심도 INT –

+1

'이름, 점수 = li.split에 합계를 호출 할 수 없습니다 :

또한 statistics 모듈과 코드를 대체하는 평균 알아서하도록 할 수 있습니다 "")'는 작동하고 dict을 defaultdict로 바꿉니다 –

+0

괜찮은 환호 @PadraicCunningham 그러면 합계 대신 무엇을합니까? –

답변

0

문자열과 정수 목록을 모두 데이터 구조에 혼합하는 것은 현명하지 않습니다. 대신 그와 같은 것을 시도해야합니다. 그러면 추가 계산에 도움이됩니다.

while choice == 'av': 
    if schClass == '1': 
    schClass = open("scores1.txt", 'r') 
    li = open("scores1.txt", 'r') 
    data = li.read().splitlines() 
    for li in data: 
     name = li.split(":")[0] 
     score = li.split(":")[1] 

     diction1.setdefault(name,[]).append(int(score)) 

    # The following loop should work, 
    # even if it can be optimized (see Padraic's answer) 
    for name in diction1: 
     student_average = sum(diction1[name])/len(diction1[name]) 
     averages_dct[name] = student_average 
    ... 

자세한 내용은 setdefault의 문서를 설정하십시오.

나는 당신의 입력 데이터 파일을 가지고 있지 않기 때문에, 정말 그것을 테스트 할 수 없습니다,하지만 그 같은 생산한다 : 코드의 나머지 부분은 지금 균일하게 가지고 작업을해야 그 후

{'Ruan': [22], 'hello': [22, 1], 'kurun': [29]} 

을 정수리스트. 같은 선수의 "득점 수"는 무엇이든간에.

+0

나에게 많은 도움을 준 건 @Sylvain Leroux –

0

defaultdict을 사용하고 목록에 모든 점수를 저장하면 합계와 평균이 더 쉬워지고, defaultdict는 이름을 추가하고 키가 존재하지 않거나 각 점수를 추가하는 경우 추가합니다 그것은 않는 경우 dict.setdefault을 사용하는 것보다 더 효율적입니다 :

from collections import defaultdict 


diction1 = defaultdict(list) 
averages_dct = {} 
student_average = {} 
while choice == 'av': # 
    if schClass == '1': # not sure what this is supposed to do 
     schClass = open("scores1.txt", 'r') 
    with open("scores1.txt") as f: 
     for li in f: # just iterate over the file object 
      name, score = li.split(":") # split once and unpack 
      # append score cast as int to the list 
      diction1[name].append(int(score)) 
    # now average scores for each using calling sum on lists of ints 
    for name,scores in diction1.items(): 
     student_average = sum(scores)/len(scores) 
     averages_dct[name] = student_average 

나는 당신의 다음 루프 우리가이 이름을 키로 평균을 사용하여 추가 defaultdict 사용할 수 있도록 다시 같은 평균 점수 이름을 찾을 수 있습니다 추정 같은 평균 :

common_dct = defaultdict(list) 
# use items to get the key and value 
for name, average in averages_dct.items(): 
    common_dct[averages_dct].append(name) 

common_dict를 실제로 사용하지 않으려는 경우 이전 루프에서 이름을 그룹화하여 점수를 키로 사용하고 이름을 추가하여 논리를 뒤집을 수 있습니다.

from statistics import mean 
for name,scores in diction1.items(): 
    student_average = mean(scores) 
    averages_dct[name] = student_average 
관련 문제