-1
option= input("alphabetically(a), high to low(b)")
if option == "a":
    with open('Class4.txt', 'r') as r:
        for line in sorted(r):
            print(line)

elif option == "b":
            def score(line):
                return int(line.split(',')[1])

            with open('Class4.txt', 'r') as r:
                for line in sorted(r, key=score, reverse=True):
                    print(line) 

I was able to display aplhabetically but was not able to display high to low the file class 4 contains variable name and score

ab 9

z 4

b 6

a10

python
  • 7
  • 6
  • 1
    Is that the exact contents of your Class4.txt file? Why are you doing `line.split(",")` when the file doesn't have any commas in it? – Kevin Oct 29 '15 at 12:58
  • You are splitting on commas instead of whitespace. – OneCricketeer Oct 29 '15 at 12:58
  • yes thats the exact contents – python Oct 29 '15 at 12:59
  • @Kevin if i remove the coma should that solve the problem – python Oct 29 '15 at 13:00
  • @python, I don't know, when you remove it does your code start working? – Kevin Oct 29 '15 at 13:02
  • @Kevin when i remove the error message goes ut nothing is displasyed – python Oct 29 '15 at 13:15
  • Wait, there was an error message? You didn't mention that before. What did it say? – Kevin Oct 29 '15 at 13:23
  • @Kevin it said Traceback (most recent call last): File "C:\Users\a\Desktop\Computing ca\task 3 aplha.py", line 14, in for line in sorted(r, key=score, reverse=True): File "C:\Users\a\Desktop\Computing ca\task 3 aplha.py", line 11, in score return int(line.split(",")) TypeError: int() argument must be a string, a bytes-like object or a number, not 'list' – python Oct 29 '15 at 21:39

1 Answers1

0

The file contains empty lines and you are trying to split it into a list and accessing the second element. This is why you are getting IndexError. So ignore the empty lines.

And also you should do line.split() since there is no comma

option= input("alphabetically(a), high to low(b)")
if option == "a":
    with open('Class4.txt', 'r') as r:
        for line in sorted(r):
            print(line)

elif option == "b":
        def score(line):
            if line != '\n':
                return int(line.split()[1])

        with open('Class4.txt', 'r') as r:
            for line in sorted(r, key=score, reverse=True):
                print(line) 
Termi
  • 641
  • 7
  • 14
  • hi the code display displays it in alphabetical order even if b is chosen it just displays it backwards – python Oct 29 '15 at 21:45
  • for this particular data the result for both options is same. Try with some other data then you will see the difference – Termi Oct 30 '15 at 05:50