Sorting csv files using python

preview_player
Показать описание
This is a short video on how to sort a "comma separated values file" aka csv file using python.
I've used csv module for this.
Why it is difficult to sort a csv file in python?
This method returns the csv class object. When we convert the csv class object into a list then the resultant list will be "list of lists".
Here comes the main problem. We know how to sort a list using sort method which belongs to list class, but when it comes to list of lists sorting becomes trickier as the value we have to sort according to, will not be readily available in the list. It will be inside the list's list. I know it sounds crazy just look at the list of list given below:
x = [ ["Rollno 1", "ABC 1", 69], [ "Rollno 2", "ABC 2", 78], [ "Rollno 3", "ABC 3", 58 ] ]
[['Rollno 1', 'ABC 1', 69], ['Rollno 2', 'ABC 2', 78], ['Rollno 3', 'ABC 3', 58]]
That's why sort() is just not enough.
We have to use a key which returns the value through which we want to sort the file. this can be done by using:

i)
import operator
ii) you can replace key by
key=lambda row: row[3]

So by the following method we can sort x:
step (i)
step (ii)
x
[['Rollno 2', 'ABC 2', 78], ['Rollno 1', 'ABC 1', 69], ['Rollno 3', 'ABC 3', 58]]

references:
code:

Meet me on::
Рекомендации по теме
Комментарии
Автор

There's an error at 3:25, when you're defining the lambda function - you have to specify that the value you're taking to sort the list must be an integer, or else, it will treat the element in alphabetical order (remember that, when handling strings, the maximum character for a number is 9). If there's a 100 in any of those values, that sort function will send it to the bottom of the list since 1 is less than 5.

The code would be like this: csv_list.sort(key= lambda l:int(l[-1]), reverse=True)

FabriGLiza
Автор

csv_list.sort(key= lambda l:l[-1], reverse=True)
IndexError: list index out of range

johnordiz