带lambda函数的sorted()

2024-04-26 18:43:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我的字符串看起来像“co1/co2”,“co3/co4”co11/co12“

将其描述为正则表达式:

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

我想根据regex的“month”组对这些字符串的集合进行排序。(字符串中的第一个数字(“co1/co2”中的“1”或“co12/co13”中的“12”)

不过,我想不出在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:]))

Tags: lambda字符串co2co1co3co4co9co6
2条回答

没有正则表达式:

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

这将获取字符串中在/之前的部分,然后除起始co之外的所有内容,然后将其转换为整数。你知道吗

我使用了^{},因为对于只拆分一次的情况,它比^{}快。你知道吗

演示:

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

试试这个:

>>> 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个索引后的值并转换为整数

相关问题 更多 >