- A+

Category：Languages

Given a list of strings, return a list with the strings in sorted order, except group all the strings that begin with 'x' first.

e.g.

`['mix', 'xyz', 'apple', 'xanadu', 'aardvark']`

yields

`['xanadu', 'xyz', 'aardvark', 'apple', 'mix']`

.

`a=['bbb', 'ccc', 'axx', 'xzz', 'xaa'] a1=['mix', 'xyz','apple', 'xanadu', 'aardvark','xz'] xlist=[] def sort(s): for i in s: if i[0]=='x': xlist.append(i) s.remove(i) print sorted(xlist)+sorted(s) del xlist[:] sort(a) sort(a1) `

This code works as long as two list elements which start with x dont come together. i.e I get proper output for list a1 but not for a can you help me understand why!

obtained output.

`['xzz', 'axx', 'bbb', 'ccc', 'xaa'] ['xanadu', 'xyz', 'xz', 'aardvark', 'apple', 'mix'] `

You can use `sorted`

or `list.sort`

with two keys:

`l = ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] sorted(l, key=lambda x: (not x.startswith('x'), x)) ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] `

where `not x.startswith('x')`

returns `bool`

, which gets sorted in `False`

first. Thus, `not x.startswith('x')`

grabs the strs that start with 'x' and bring them to the front.