Sorted () with lambda function

I have lines that look like "co1 / co2", "co3 / co4" ... "co11 / co12"

describing it as a regular expression:

^(?P<prefix>\w\w)(?P<month>\d+)/(?P<prefix2>\w\w)(?P<month2>\d+)$   

I want to sort the collection of these strings based on the equivalent of the month group of the regular expression. (first number in a line (for example, "1" in "co1 / co2" or "12" in "co12 / co13")

I cannot calculate the lambda function that I can use in sorted (), which will do this for me.

wrong_order = [u'co1/co2', u'co10/co11', u'co11/co12', u'co12/co13', u'co2/co3',
       u'co3/co4', u'co4/co5', u'co5/co6', u'co6/co7', u'co7/co8', u'co8/co9',
       u'co9/co10']


correct_order = [u'co1/co2', u'co2/co3', u'co3/co4', u'co4/co5', u'co5/co6', \
u'co6/co7', u'co7/co8', u'co8/co9', u'co9/co10', u'co10/co11', u'co11/co12', u'co12/co13']


#this lambda function doesn't work
output = sorted(wrong_order, key=lambda x: (x[2:]))
+4
source share
2 answers

Without regex:

lambda x: int(x.partition('/')[0][2:])

/, , co, .

str.partition(), , str.split() .

:

>>> wrong_order = [u'co1/co2', u'co10/co11', u'co11/co12', u'co12/co13', u'co2/co3',
...        u'co3/co4', u'co4/co5', u'co5/co6', u'co6/co7', u'co7/co8', u'co8/co9',
...        u'co9/co10']
>>> sorted(wrong_order, key=lambda x: int(x.partition('/')[0][2:]))
[u'co1/co2', u'co2/co3', u'co3/co4', u'co4/co5', u'co5/co6', u'co6/co7', u'co7/co8', u'co8/co9', u'co9/co10', u'co10/co11', u'co11/co12', u'co12/co13']
+5

:

>>> sorted(wrong_order, key = lambda x:int(x.split("/")[0][2:]))
[u'co1/co2', u'co2/co3', u'co3/co4', u'co4/co5', u'co5/co6', u'co6/co7', u'co7/co8', u'co8/co9', u'co9/co10', u'co10/co11', u'co11/co12', u'co12/co13']

Lambda, , "/" 1

+3

Source: https://habr.com/ru/post/1611568/


All Articles