Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort a list using lambda and regex in python

list = ['xxxx ResultDatetime:2017-05-31 09:38:00.000:ResultDatetime', 'xxxx ResultDatetime:2017-05-26 15:36:00.000:ResultDatetime', 'yyyyy' ResultDatetime:2017-10-23 16:16:00.000:ResultDatetime]

datet = re.compile(r'ResultDatetime:(\d{4}-\d{2}-\d{2} \d{2}:\d{2})')

list.sort(key = lambda x: ........)

I want to sort the lists in an order starting with the earliest date. How should I go about it using lambda and regex?

like image 333
dratoms Avatar asked Feb 13 '26 02:02

dratoms


1 Answers

With the code you have there it is sufficient to do:

list.sort(key=lambda x: datet.search(x).group(1))

(but please, don't use list as a variable name).

There is no need to convert the extracted string to a datetime as it is already in a format that will sort naturally.

Note however that if any string does not match the regex this will generate an error, so you may be better to split the key out into a named multi-line function and test for a successful match before returning the matched group.

def sort_key(line):                                                                                                                                               
    match = datet.search(line)                                                                                                                                               
    if match:                                                                                                                                                     
        return match.group(1)                                                                                                                                                    
    return ''        

data = [
    'xxxx ResultDatetime:2017-05-31 09:38:00.000:ResultDatetime',
    'xxxx ResultDatetime:2017-05-26 15:36:00.000:ResultDatetime',
    'yyyyy ResultDatetime:2017-10-23 16:16:00.000:ResultDatetime'
]
data.sort(key=sort_key) 
like image 117
Duncan Avatar answered Feb 15 '26 15:02

Duncan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!