问题
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))
回答1:
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.
回答2:
Use lambda
:
sorted(my_entries_list,
key=lambda e: datetime.combine(e.created_date, e.created_time))
回答3:
From the documentation
key specifies a function of one argument that is used to extract a comparison key from each list element
eg.
def combined_date_key(elem):
return datetime.datetime.combine(v.created_date, v.created_time)
entries.sort(key=combined_date_key)
(this is identical to the lambda already posted, just broken out for clarity).
Your other option is to use the cmp
argument (it's not required here, but for a sufficiently expensive key function which can be short-circuited, this could be faster)
回答4:
It may be slightly faster to use a tuple like this:
sorted(my_entries_list,
key = lambda e: (e.created_date, e.created_time))
Then things will be sorted by date, and only if the dates match will the time be considered.
来源:https://stackoverflow.com/questions/14198382/sorting-python-list-based-on-key