1

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

Binit Singh
  • 973
  • 4
  • 14
  • 35

2 Answers2

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

falsetru
  • 357,413
  • 63
  • 732
  • 636
0

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Saher Ahwal
  • 9,015
  • 32
  • 84
  • 152