2015-10-14 58 views
4

我有一個字符串,看起來像「CO1/CO2」, 「CO3/CO4」 ... 「CO11/CO12」排序()與lambda函數

將其描述爲一個正則表達式:

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

我想基於正則表達式的「月」組的等價物對這些字符串的集合進行排序。 (字符串中的第一個數字(例如,「co1/co2」中的「1」或「co12/co13」中的「12」)

我無法弄清楚我可以使用的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:])) 
+0

如果數字始終具有相同的數字位數,則您的解決方案將起作用。例如'co02'而不是'co2' – Pynchia

+0

你想要的是數字排序,但'x [2:]'是一個字符串。您需要將該字符串轉換爲數字 –

回答

5

沒有一個正則表達式:

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

試試這個:

>>> 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個指數選擇的價值和轉換整數