0

I have a CSV file containing values like a | b | c | 8 and n | 8 | p | 4 as so on. I would like to know as to how do I sort them considering the last element in each row as the index?

Ex: sorted order for the above would be n | 8 | p | 4 and a | b | c | 8

I am using Python csv reader to read the file and want to apply Quick sort. I split the CSV with '|' but not quite sure how do I proceed from here. Or if splitting isn't the correct thing to do? Can someone shed some light as to how I should be doing it?

Bhargav Panth
  • 301
  • 1
  • 3
  • 10
  • How often do you need to do this? How many other manipulations with table data like this will you be doing? Because it might be practical to install the [pandas package](http://pandas.pydata.org/) and use that. –  May 31 '16 at 06:24
  • 2
    If you're on a *nix command line, a simple `sort -k4 -t'|' input_file.csv` would do the trick, btw. –  May 31 '16 at 06:25
  • @Evert The idea is to sort these records on a regular basis since there will be a lot more records pumped into the csv regularly. (Usually around 10 - 20 times a day) Once I have these records sorted, I need to be applying other small operations which isn't all that resource intensive. – Bhargav Panth May 31 '16 at 06:40

1 Answers1

1

If you have a list of lists you could use the pre built sorting function, which should be faster than anything you can implement yourself.

There is a command in sort which then does exactly what you want:

sorted(yourArray, key=lambda x: x[3])
#sort yourArray by the 4th value in every list

So what I would do is:

  • Read csv and split it with ' | '
  • Save all lines you read in a list
  • use the above function which returns a new list (it is not in place sorting)

Edit

Just saw the new comments, and if you want to add new entries and keep your List sorted, you should look into the bisec module.

It is used for inserting values into an already sorted list, but does not support the key operator. They explain how to use it for lists of your type in the last paragraph of the link.

Jan
  • 1,504
  • 10
  • 15