Manish Gupta
Manish Gupta

Reputation: 4656

python sort lists from 1 list based on date elements

I have 3 lists. Currently I am using 1 list to sort all list like this:

sorted_lists = sorted(zip(new_date_list, flipkart_sale_list, paytm_sale_list), key=lambda x: x[0])
new_date_list, flipkart_sale_list, paytm_sale_list = [[x[i] for x in sorted_lists] for i in range(3)]

The new date list contains date strings as element which are in format of %b %d.

new_date_list = ['Feb 01', 'Feb 02', 'Jan 04', 'Jan 05', 'Jan 06', 'Jan 07']
flipkart_sale_list = [5000,4000,3000,6000,1000,9000]
paytm_sale_list = [2200,2500,3500,5000,4000,1000]

However The above code is not sorting the date string properly. So how to sort the all the lists according to new_date_lists?

The other two lists contains numbers.

Expected Result:

new_date_list = ['Jan 04', 'Jan 05', 'Jan 06', 'Jan 07', 'Feb 01', 'Feb 02']
flipkart_sale_list = [3000,6000,1000,9000,5000,4000]
paytm_sale_list = [3500,5000,4000,1000,2200,2500]

Upvotes: 3

Views: 793

Answers (2)

Muhammad Tahir
Muhammad Tahir

Reputation: 5174

Convert to datetime objects before sort. Try

sorted_lists = sorted(zip(new_date_list, flipkart_sale_list, paytm_sale_list), key=lambda x: datetime.datetime.strptime(x[0], "%b %d"))
new_date_list, flipkart_sale_list, paytm_sale_list = [[x[i] for x in sorted_lists] for i in range(3)]

Result:

>>> new_date_list
['Jan 04', 'Jan 05', 'Jan 06', 'Jan 07', 'Feb 01', 'Feb 02']
>>> flipkart_sale_list
[1000, 9000, 5000, 4000, 3000, 6000]
>>> paytm_sale_list
[4000, 1000, 2200, 2500, 3500, 5000]

As suggested by @StefanPochmann, this

new_date_list, flipkart_sale_list, paytm_sale_list = [[x[i] for x in sorted_lists] for i in range(3)]

can also be done by zip

new_date_list, flipkart_sale_list, paytm_sale_list = map(list, zip(*sorted_lists))

Upvotes: 4

Ohad the Lad
Ohad the Lad

Reputation: 1929

I did not really get the 3 lists purpose but if u got one big list do this trick.

import datetime

sorted(new_date_list, key=lambda x: datetime.datetime.strptime(x, '%b %d'))

**edit - after u've added the lists data example - i'd do the sort 3 times

Upvotes: 0

Related Questions