0

I have a list of lists containing datetime object.

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)]
 [].....
]

I am populating this list of lists, so that I can utilize this to do two things:

  • create a pretty table using prettyTable module
  • use this to create a .csv file

Problem:

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?

Jason
  • 2,278
  • 2
  • 17
  • 25
polyglot
  • 57
  • 11

2 Answers2

4

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]))
Rok Povsic
  • 4,626
  • 5
  • 37
  • 53
2

You can use list = sorted(list, key=...) or list.sort(key=...).

First method lets you use slicing to get/set only part of list - without changing first row.

import datetime

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) ]
]

table_of_list[1:] = sorted(table_of_list[1:], key=lambda x: x[4])

print(table_of_list)
furas
  • 134,197
  • 12
  • 106
  • 148