2015-01-14 2 views
0

나는 (비단뱀) CSV 파일을 인쇄하기 위해이 코드를 작업 중이다. 첫 번째 선택은 잘 작동하고 그것을 알파벳순으로 정렬합니다. 그러나 Choice 2 섹션에서 csv 파일을 가장 높은 점수로 정렬해야합니다. 텍스트/csv 파일 (선택 2에서 잘못된 점은 무엇입니까?

name, score, out of: 

Ben,5,20 
James,6,20 
Adam,12,20 
Will,20,20 

코드 :

import operator 
import csv 

file = open("scores.txt", "r") 

scores = csv.reader(file, delimiter=",") 

sort = sorted(scores) 
for i in range(0, len(sort)): 
    sort[i].append((max(sort[i][1:2]))) 

#Alphabetical Order 
choice = input("Choice: ") 

if choice == "1": 
    sort = list(sorted(sort,key = operator.itemgetter(0), reverse=False)) 

    print("\nAlphabetical Order:") 
    print("===================") 
    for i in range(0, len(sort)): 
     print("Name: ", sort[i][0], "\tScore: ", sort[i][1]) 

#Highest score 
#sort = sorted(scores) 
elif choice == "2": 


    print("\nHigh Scores:") 
    print("============") 
    sort = list(sorted(sort,key = operator.itemgetter(1, 2),reverse=True)) 
    for i in range(0, len(sort)): 
     print("Name:", sort[i][0], "\tScore:", sort[i][1], "Out of", sort[i][2]) 

답변

-1

귀하의 "선택"정수로오고, 당신은 문자열과 비교, 그래서 정확한 비교는 다음과 같습니다

모든
if str(choice) == "1": 
    #do something 
elif str(choice) == "2": 
    #do something 
+1

가 is''로 문자열을 비교하지 않습니다. 그건 정체성 때문이야. http://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce –

+0

예, 올바르게 맞았습니다. – BigBang

+0

그게 아마도 큰 문제는 아닙니다. op 코드. 그가'python 3.x'를 사용한다면,'input()'은 문자열을 반환합니다. 그러나 파이썬의 이전 버전을 작업하고있는 경우에는 지적 해 두어야 할 가치가 있습니다. – VHarisop

0

첫째 :

max(sort[i][1:2]) 

은 요소 쌍 1에서 2-1까지 반환하기 때문에 숫자 쌍 중 첫 번째 숫자 만 반환합니다. (그들이 csv.reader에서 반환로) 당신은 그러나

max(sort[i][1:3]) 

로 변경 수, .csv 파일의 숫자에 해당하는 필드는 문자열입니다. 정렬 할 때 int로 바꾸는 것을 고려해야합니다. 키로 번호 쌍에 해당하는 정수의 튜플을 사용

sort = sorted(sort, key = lambda x: (int(x[1]), int(x[2])), reverse = True) 
# no need to put the rvalue in list() 

다음 operator 꼬추를 사용하지 않고 쉬운 방법은 INT의 튜플에 문자열 쌍을 매핑하는 익명 함수를 사용하고 있습니다. 또한 python 2.x을 사용하는 경우 012B으로 전환하거나 input을 사용하고 str(choice)을 사용해야합니다. BigBang의 답변에 나와 있습니다.

번호 쌍에 따라 정렬 할 때 키 선택이 작동하지 않는 이유를 보려면 문자열 쌍의 csv.reader에서 숫자 쌍이 반환된다는 점에 유의하십시오 (예 : [ 'Name', '12' '20']). 문자열을 사 전적으로 비교하기 때문에

>>> ('12', '20') > ('6', '20') 
False 

이 비교가 12 > 6의 경우 준수하지 : 그것은 것을 쉽게 알 수있다. 여기서 '1'은 '6'보다 작습니다.

0

첫 번째 부분이 작동하면 분명히 python3을 사용하고 있습니다. 알파벳순으로 정렬하려면 이름을 먼저 정렬해야합니다. 점수별로 정렬하려면를 int로 형변환해야합니다.

with open("scores.txt") as f: 
    headers = next(f)# skip header 
    scores = list(csv.reader(f, delimiter=",")) 
    inp = input("Choose 1 for alpha sort or 2 for highscore sort") 

    if inp == "1": 
     print("\nAlphabetical Order:") 
     scores.sort() 
     for name,score,out in scores: 
      print("Name: {} score: {} out of {}".format(name,score,out)) 

    elif inp == "2": 
     print("\nHigh Scores:") 
     print("============") 
     scores.sort(key=lambda x:int(x[1]),reverse=True) 
     for name,score,out in scores: 
      print("Name: {} score: {} out of {}".format(name,score,out)) 

출력 :

Alphabetical Order: 
=================== 
Name: Adam score: 12 out of 20 
Name: Ben score: 5 out of 20 
Name: James score: 6 out of 20 
Name: Will score: 20 out of 20 
High Scores: 
============ 
Name: Will score: 20 out of 20 
Name: Adam score: 12 out of 20 
Name: James score: 6 out of 20 
Name: Ben score: 5 out of 20 
관련 문제