Python sort array of string with integers inside

匿名 (未验证) 提交于 2019-12-03 09:19:38

问题:

How i can use python to sort the list format

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

like this way

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

edit: If the array is a list of list then how can we do that like this one

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

回答1:

>>> 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 is a builtin function. Do not use it as a variable name. It will shadow the builtin function.



回答2:

you can create an intermediate array that looks like the following:

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

then you can use sorted on intermediate which will sort by first value by default.

then get back to your format.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!