2

My teacher has told me to put reverse = True to make it sort highest to lowest but I really don't know where. My code is shown below.

import csv

f = open ('sort.txt')
csv_f = csv.reader(f)
newlist = []
for row in csv_f:
    row[1] = int(row[1])
    row[2] = int(row[2])
    row[3] = int(row[3])

    sort = sorted(row[1:4])
    row.append(sort)
    newlist.append(row[0:8])
print(newlist)

Can anyone please tell me where I would put reverse = True to make it print the scores highest to lowest?

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
anomoyus
  • 33
  • 1
  • 7
  • 2
    You should read this https://docs.python.org/2/library/functions.html#sorted – Forge Mar 04 '16 at 15:54
  • 3
    BTW, it's not a good idea to use `sort` as a variable name, since that shadows the built-in `sort` function. Also, the usual Python convention is to use 4 spaces per indentation level. – PM 2Ring Mar 04 '16 at 15:59
  • 1
    @PM2Ring: There is no built-in `sort` function in Python. `sort` exists only as a method for some objects. Nevertheless it's a bad name to describe the content of the list. – Matthias Mar 04 '16 at 18:07

2 Answers2

4

You can do:

sort = sorted(row[1:4], reverse=True)
Will
  • 4,299
  • 5
  • 32
  • 50
  • 1
    @anomoyus: I hope you make the effort to understand why this works. Just parroting code from the Internet doesn't help you learn. – Fred Larson Mar 04 '16 at 16:02
2

sorted() is a built-in function in Python. It has optional keyword arguments 'key' and 'reverse'. Your instructor is referring to applying the keyword argument as an input to the sorted() function. Check out more about optional arguments here.

As you can see from documentation, passing in a value for reverse follows this behavior:

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

PS: as PM 2Ring mentions, I would discourage you from using 'sort' as a variable name because it is a built-in method of the list type. You can read more about naming specifications in the style guide.

hpatel826
  • 41
  • 5