Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting python list based on key

I have some Entrys in a python list.Each Entry has a creation date and creation time.The values are stored as python datetime.date and datetime.time (as two separate fields).I need to get the list of Entrys sorted sothat previously created Entry comes before the others.

I know there is a list.sort() function that accepts a key function.In this case ,do I have to use the date and time to create a datetime and use that as key to sort()? There is a datetime.datetime.combine(date,time) for this. But how do I specify this inside the sort function?

I tried key = datetime.datetim.combine(created_date,created_time)

but the interpreter complains that the name created_date is not defined

class Entry: 
   created_date = #datetime.date
   created_time  = #datetime.time
   ...

my_entries_list=[Entry1,Entry2...Entry10]
my_entries_list.sort(key = datetime.datetim.combine(created_date,created_time))
like image 991
damon Avatar asked Dec 21 '22 11:12

damon


1 Answers

You probably want something like:

my_entries_list.sort(key=lambda v:
                           datetime.datetime.combine(v.created_date, v.created_time))

Passing datetime.datetime.combine(created_date, created_time) tries to call combine immediately and breaks since created_date and created_time are not available as local variables. The lambda provides delayed evaluation: instead of executing the code immediately, it creates a function that will, when called, execute the specified code and return the result. The function also provides the parameter that will be used to access the created_date and created_time attributes.

like image 161
user4815162342 Avatar answered Jan 03 '23 02:01

user4815162342