简体   繁体   English

sorted()与lambda函数

[英]sorted() with lambda function

I have strings that look like "co1/co2", "co3/co4" ... "co11/co12" 我的字符串看起来像“co1 / co2”,“co3 / co4”......“co11 / co12”

describing it as a regex: 将其描述为正则表达式:

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

I want to sort a collection of these strings based on the equivalent of the "month" group of the regex. 我想根据正则表达式的“月”组的等价物对这些字符串的集合进行排序。 (the first number in the string (eg. the "1" in 'co1/co2' or the "12" in 'co12/co13') (字符串中的第一个数字(例如,'co1 / co2'中的“1”或'co12 / co13中的“12”)

I'm unable to figure out a lambda function I can use in sorted() that will do this for me, though. 我无法弄清楚我可以在sorted()中使用的lambda函数,但是我会这样做。

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:]))

Without a regex: 没有正则表达式:

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

This takes the part of the string before the / , then everything but the starting co , then converts that to an integer. 这将在/之前获取字符串的一部分,然后除了起始co所有内容,然后将其转换为整数。

I used str.partition() as it is faster than str.split() for the split only once case. 我使用str.partition()因为它比str.split()更快, 只有一次拆分

Demo: 演示:

>>> 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']

try this: 尝试这个:

>>> 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 whats it doing, first it split with "/" and select the 1st value and select the value after 1 index and convert to integer Lambda它做什么,首先用“/”拆分并选择第一个值并选择1个索引后的值并转换为整数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM