user5063976
user5063976

Reputation:

Python reordering the list of lists after sorting

I'm fetching data from two separate tables as shown below.

list_table_1 = models.my_table_1.objects.all().order_by("-date_field","time_field") ## data from table 1
list_table_2 = models.my_table_2.objects.all().order_by("-date_field","time_field") ## data from table 2

Then I put both the lists in single list say my_list and would like to sort them based on the date and also the time in reverse order such that the most recent order is on top. So I did this : my_list(key= lambda item:item[0][1],reverse= True)

then I get this :

[['InstaMojo', datetime.date(2015, 6, 30), datetime.time(10, 50, 54), u'status',u'buyer_name'], ['InstaMojo',datetime.date(2015, 6, 29), datetime.time(19, 46, 22), u'status', u'buyer_name'],['PayU',datetime.date(2015, 6, 30), datetime.time(15, 39, 11), u'status', u'firstname'], ['PayU', datetime.date(2015, 6, 29), datetime.time(15, 37, 29), u'status', u'firstname']]

But I need output like the following:

[['PayU',datetime.date(2015, 6, 30), datetime.time(15, 39, 11), u'status', u'firstname'],['InstaMojo', datetime.date(2015, 6, 30), datetime.time(10, 50, 54), u'status',u'buyer_name'] ,['InstaMojo',datetime.date(2015, 6, 29), datetime.time(19, 46, 22), u'status', u'buyer_name'], ['PayU', datetime.date(2015, 6, 29), datetime.time(15, 37, 29), u'status', u'firstname']]

Any help in this regard would be great! Thanks in advance!

BTW I have looked into these questions on SO - link 1 and link 2

Upvotes: 1

Views: 118

Answers (3)

Derek T. Jones
Derek T. Jones

Reputation: 1822

This produces the output you want:

my_list = sorted(my_list, key=operator.itemgetter(1, 2), reverse=True)

What you have in your code is sorting by the second item of the first item: item[0] is the first item, and item[0][1] is the second item of that. So you were sorting by the 'n' in 'Instamojo', the 'a' in 'PayU', etc.

operator.itemgetter has the semantics you're looking for; it selects a tuple from the input, in this case, (second-item, third-item). Then sorted (or list.sort) sorts them lexicographically, so that if the dates are the same, they are compared by time.

Upvotes: 1

shaktimaan
shaktimaan

Reputation: 1857

Your key seems to be wrong.

lambda item:item[0][1]

will always give you the first charachter of element at [0] th index. If ypu wish to sort on basis of date use this as key.

key= lambda x :x[1]

Upvotes: 1

John La Rooy
John La Rooy

Reputation: 304147

You should create a tuple (date, time) for each key

my_list.sort(key=lambda x:(x[1], x[2]), reverse=True)

Upvotes: 2

Related Questions