2014-02-27 80 views
1

整數如何使用Python來排序列表格式Python的排序陣列內

format=["12 sheet","4 sheet","48 sheet","6 sheet", "busrear", "phonebox","train"] 

像這樣

format =["4 sheet", "6 sheet", "12 sheet", "48 sheet", "busrear, "phonebox", "train"] 

編輯:如果數組列表的名單,然後怎麼樣我們是這樣做的一個

format=[[1L, u'12 sheet', 0],[2L, u'4 sheet', 0], [3L, u'48 sheet', 0], [4L, u'6 sheet', 0 [5L, u'Busrear', 0], [6L, u'phonebox', 0], [7L, u'train', 0]]

回答

5
>>> fmts =["12 sheet","4 sheet","48 sheet","6 sheet", "busrear", "phonebox","train"] 
>>> fmts.sort(key=lambda x: (int(x.split(None, 1)[0]) if x[:1].isdigit() else 999, x)) 
>>> fmts 
['4 sheet', '6 sheet', '12 sheet', '48 sheet', 'busrear', 'phonebox', 'train'] 

format是內建函數。不要將其用作變量名稱。它會影響內建功能。

+0

'x [0] .isdigit()'?!? – thefourtheye

+3

@thefourtheye,使用'x [:1]'來防止IndexError。 – falsetru

+0

啊。很好:)謝謝 – thefourtheye

0

您可以創建一箇中間數組,如下所示:

intermediate = [(12, "sheet"), (4, "sheet"), ... ] 

,那麼你可以使用intermediate排序將排序第一個值默認。

然後回到你的格式。