ayush nigam
ayush nigam

Reputation: 95

how to arrange a list in the order of index od another sorted list in python?

I have 2 lists say,

dates=['4/21/2015', '10/14/2014', '9/16/2014', '7/10/2014', '8/11/2014', '8/3/2014', '7/20/2014', '7/6/2014', '4/21/2015', '4/21/2015']
events=[a,b,c,d,e,f,g,h,i,j]

I sorted list dates in chronological order and put the valus in List dates1

dates1=['7/6/2014', '7/10/2014', '7/20/2014', '8/3/2014', '8/11/2014', '9/16/2014', '10/14/2014', '4/21/2015', '4/21/2015', '4/21/2015']

now how do I arranges the events in the same chronological order as dates1?

Upvotes: 2

Views: 525

Answers (3)

rkp
rkp

Reputation: 438

Another way is to use numpy's argsort function, though it requires you to convert your events list to an array.

import numpy as np
from datetime import datetime

dates = ['4/21/2015', '10/14/2014', '9/16/2014', '7/10/2014', '8/11/2014', '8/3/2014', '7/20/2014', '7/6/2014', '4/21/2015', '4/21/2015']
events = np.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'])

datetimes = [datetime.strptime(date, '%m/%d/%Y') for date in dates]
events_sorted = events[np.argsort(datetimes)]

print(events_sorted)

Upvotes: 0

junnytony
junnytony

Reputation: 3515

This will do it:

sortedevents = sorted(zip(dates, events), key = lambda i: dates1.index(i[0]))

First we combine the dates and events into matching tuples and then we sort the tuples using the sorted list dates1

To get the sorted list of events by itself:

events = [e[1] for e in sortedevents]

Anand's answer may be preferred since it removes the need to have a separate sorted list of dates, i.e. no need to have dates1

Upvotes: 0

Anand S Kumar
Anand S Kumar

Reputation: 90899

The easiest way to go about this would be to zip both the lists together and then sort them based on the date conversions for the dates array.

Example -

>>> from datetime import datetime
>>> dates=['4/21/2015', '10/14/2014', '9/16/2014', '7/10/2014', '8/11/2014', '8/3/2014', '7/20/2014', '7/6/2014', '4/21/2015', '4/21/2015']
>>> events=['a','b','c','d','e','f','g','h','i','j']
>>> s =  sorted(zip(dates, events), key = lambda x: datetime.strptime(x[0],'%m/%d/%Y'))
>>> s
[('7/6/2014', 'h'), ('7/10/2014', 'd'), ('7/20/2014', 'g'), ('8/3/2014', 'f'), ('8/11/2014', 'e'), ('9/16/2014', 'c'), ('10/14/2014', 'b'), ('4/21/2015', 'a'), ('4/21/2015', 'i'), ('4/21/2015', 'j')]

Then you can get the list of events sorted using list comprehension as -

>>> sortedevents = [x[1] for x in s]
>>> sortedevents
['h', 'd', 'g', 'f', 'e', 'c', 'b', 'a', 'i', 'j']

What zip function does is that it combines the elements at the same indexes from the lists (iterables) provided to it as parameter into a list of tuples (each tuple at ith position containing the combination of elements at ith position from the lists provided in parameter).

Upvotes: 2

Related Questions