2015-02-03 3 views
-2

이 작업을 해결하려고 할 때 문제가 발생하여 몇 번 실패한 후에 여기 키가 다중 값을 저장할 때 키 (이름)에 대해서만 가장 높은 값 (점수)을 인쇄 할 수 있는지 궁금합니다. 예 :키의 가장 높은 값만 인쇄하는 방법은 무엇입니까?

Rob Scored: 3,5,6,2,8 
Martin Scored: 4,3,1,5,6,2 
Tom Scored: 7,2,8 

이름은 키이고 점수는 값입니다. 나는 그것이 알파벳 순서를 무시하는 것 max 기능을 시도하지만 때 지금은

Martin Scored: 6 
Rob Scored: 8 
Tom Scored: 8 

의 출력을 얻을 싶습니다. 측면이 아니라 다른 요구 사항도 이후 단계에서 저장해야한다는 요구 사항입니다.

from collections import OrderedDict 
dictionary = {} 

for line in f: 
    firstpart, secondpart = line.strip().split(':') 
    dictionary[firstpart.strip()] = secondpart.strip() 
    columns = line.split(": ") 
    letters = columns[0] 
    numbers = columns[1].strip() 
    if d.get(letters): 
     d[letters].append(numbers) 
    else: 
     d[letters] = list(numbers) 
sorted_dict = OrderedDict(
sorted((key, list(sorted(vals, reverse=True))) 
     for key, vals in d.items())) 
print (sorted_dict) 
+1

이 질문은 오늘 요청되었습니다. 이상한 점 : D – nbro

+0

입력 파일은 어떻게 생겼습니까? – skrrgwasme

+0

은 txt 파일이며 'Rob Scored : ....'의 첫 번째 강조 표시된 예제처럼 보입니다. rob이 키이고 점수가 값인 경우 –

답변

0

이 당신이 원하는 것을 수행합니다

# You don't need to use an OrderedDict if you only want to display in 
# sorted order once 
score_dict = {} # try using a more descriptive variable name 

with open('score_file.txt') as infile: 
    for line in infile: 
     name_field, scores = line.split(':') # split the line 
     name = name_field.split()[0]   # split the name field and keep 
              #  just the name 

     # grab all the scores, strip off whitespace, convert to int 
     scores = [int(score.strip()) for score in scores.split(',')] 

     # store name and scores in dictionary 
     score_dict[name] = scores 

     # if names can appear multiple times in the input file, 
     # use this instead of your current if statement: 
     # 
     # score_dict.setdefault(name, []).extend(scores) 

# now we sort the dictionary keys alphabetically and print the corresponding 
# values 
for name in sorted(score_dict.keys()): 
    print("{} Scored: {}".format(name, max(score_dict[name]))) 

이 문서를 읽기주십시오 : Code Like a Pythonista합니다. 그것은 더 나은 코드를 작성하는 방법에 대한 많은 제안을 가지고 있으며, 여기서 값이 목록 인 사전을 다루는 방법을 배운 곳이 dict.setdefault()입니다.

또 다른 참고로, 귀하의 질문에 max 기능을 사용하려는 시도가 언급되었지만 귀하가 제공 한 코드에는 그 기능이 없습니다. 질문에서 무언가를 성취하려는 실패한 시도를 언급한다면, 실패한 코드도 포함시켜 디버깅을 도울 수 있습니다. 몇 가지 다른 제안 사항과 함께 작업을 수행하는 몇 가지 코드를 제공 할 수 있었지만 제공하지 않으면 원래 코드를 디버깅 할 수 없습니다. 이것은 분명히 숙제 문제이기 때문에 왜 처음에는 제대로 작동하지 않았는지 알아내는 데 시간을 할애해야합니다.

관련 문제