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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

@thefourtheye, Used x[:1] to prevent IndexError.
Wouldn't that be better if else x instead of else 999?
@thefourtheye, You can't compare int with str in Python 3.x; causes TypeError: unorderable types: str() < int()
@thefourtheye, Specific version is not mentioned. So I provided a solutioni that can be run both in Python 2.x/3.x.
Hey thanks for answer but if the list will be a list of list then how we will sort it
|
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.