polyglot polyglot - 1 year ago 75
Python Question

sorting list of list containing datetime.date in increasing/decreasing order to create pretty table/csv file

I have a list of list containing date time object of the format:

table_of_list= [[name, email, address, details, date_last_contacted],
[u'Jane Doe', u'jdoe@abc.com', u'sillybilly', u'dodo', datetime.date(2016, 11, 1)]
[u'John Doe', u'jedoe@abc.com', u'123 house',u'random', dateTime.date(2016,10,1)]

background and what I am trying to do:
I am populating this list of list myself, so that I can utilize this to do two things:
- create a pretty table using prettyTable module
- use this to create a csv file

I need to organize the way the rows are being displayed sorted by the date_last_contacted order in both pretty table and csv.
Pretty table sort is not working for me maybe because I have a header. But not entirely sure.
I am new to python, not sure how the lambda thing works, but can i some how sort the list of lists before utilizing it to create csv file or pretty table.

In short, How can I sort the lists within the table_of_list in the most pythonic way! Will be greatful for any help extended.

-python newbie

Answer Source

You can use sorted function where you set key to a lambda function that returns the last element - to sort by the last element.

We take the first row of the original table as a header and then add the rest of the rows, which are sorted.

sorted_table = [table_of_list[0]]
sorted_table.extend(sorted(table_of_list[1:], key=lambda row: row[-1]))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download