0

I have two lists time_list with datetime and name_list with names mapped to each other respectively.

    time_list = [datetime.datetime(2020, 3, 28, 18, 49, 36, tzinfo=tzutc()),
    datetime.datetime(2020, 3, 28, 18, 54, 53, tzinfo=tzutc()),
    datetime.datetime(2020, 3, 28, 19, 5, 28, tzinfo=tzutc()),
    datetime.datetime(2020, 3, 28, 18, 59, 56, tzinfo=tzutc()),
    datetime.datetime(2020, 3, 28, 18, 55, 42, tzinfo=tzutc())]


    name_list = [a,b,c,d,e]

How to find the which name_list has the most recent time in the time_list ?

In above example: time_list[2] has the most recent w.r.t name_list[2]

Expected output:

        most_recent_name_list = ['c']

2 Answers2

1

zip the two lists, this will give you tuples (date, name). Take the max of these tuples (they will be sorted by date first, then by name) and extract the name from the max:

import datetime
from dateutil.tz import tzutc

time_list = [datetime.datetime(2020, 3, 28, 18, 49, 36, tzinfo=tzutc()),
    datetime.datetime(2020, 3, 28, 18, 54, 53, tzinfo=tzutc()),
    datetime.datetime(2020, 3, 28, 19, 5, 28, tzinfo=tzutc()),
    datetime.datetime(2020, 3, 28, 18, 59, 56, tzinfo=tzutc()),
    datetime.datetime(2020, 3, 28, 18, 55, 42, tzinfo=tzutc())]


name_list = ['a', 'b', 'c', 'd', 'e']

max(zip(time_list, name_list))[1]
#'c'
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
0

You can use sorted function and pass a range equal to length of original list as index, for keys, you can pas dates as key and perform reverse sort like following to get original indexes for sorted dates and use those index to get latest date from other list

sorted_list = sorted(range(len(time_list)),key=time_list.__getitem__,reverse=True)

and you can get index of sorted as

name_list[sorted_list[0]]
A.B
  • 20,110
  • 3
  • 37
  • 71
  • Based on most recent datetime in time_list, get the value from the other. In above ex, three value in time_list is most recent which is equal to third in name_liat –  Mar 28 '20 at 19:53