0

I have been working on this code (in python) to print a CSV file, sorted. The first choice works fine and sorts it Alphabetically. However the Choice 2 section is supposed to sort the csv file to the highest score. The text/csv file (

name, score, out of:

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

code:

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])
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140

3 Answers3

0

First of all:

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

will return just the first of the pair of numbers, because the slice returns elements 1 through 2-1. You could change it to

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

However, the fields that correspond to numbers in the .csv file are strings (as they are returned from csv.reader). You should consider turning them to ints when sorting. An easy way without using the operator thingy is using an anonymous function that maps a string pair to a tuple of ints:

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

which uses as key a tuple of integers that correspond to your number pair. Also, if you are using python 2.x, you should either switch to raw_input or use input and use str(choice), as BigBang's answer points out.

To see why your key choice does not work when sorting according to the number pair, keep in mind that the number pair is returned from csv.reader in a list of strings (like ['Name', '12', '20']). It's easy to see that:

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

This comparison fails to comply with the case of 12 > 6 because strings are compared lexicographically. Here, '1' is smaller than '6'.

VHarisop
  • 2,816
  • 1
  • 14
  • 28
0

If the first part works then obviously you are using python3, you just need to sort scores to sort alphabetically as the names come first. To sort by score you need to cast the to an 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))

Output:

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
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
-1

Your "choice" is coming as integer, and you are comparing it with string, so the correct comparison will be:

if str(choice) == "1":
   #do something
elif str(choice) == "2":
   #do something
BigBang
  • 149
  • 12
  • 1
    don't compare strings with `is`. that's for identity. http://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce – Karoly Horvath Jan 14 '15 at 14:30
  • That is probably not the major problem in the op's code. If he uses `python 3.x`, `input()` returns a string. However it was worth pointing out in the case he is working on earlier versions of python. – VHarisop Jan 14 '15 at 14:41
  • That was unknown to me also, Thanks for Informing – BigBang Jan 14 '15 at 14:42
  • @VHarisop, how could the first part work if the OP is using python2? – Padraic Cunningham Jan 14 '15 at 14:58