-2

I am new to Python.I want to sort a list with certain condition. ex:

I am getting the environment details and storing them as list as below. ls = ['qa','uat','prod','dev'] They can be any order. ls = ['uat','qa','dev','prod']

But the result list should be:

rls = ['prod','qa','uat','dev']
Kousik
  • 21,485
  • 7
  • 36
  • 59
Amit Mallick
  • 7
  • 1
  • 3

2 Answers2

0

AFAIK, you can define custom lambda functions and send them as key argument to the sorted function in python as :

sorted(list,key = lambdafn)

this lambda fn should have boolean return value, will not work otherwise.

finally got hold of the documentation, see more here : https://wiki.python.org/moin/HowTo/Sorting/

PS : Sorry about poor answer style,first ever answer in SO

Giridhur
  • 164
  • 7
0

You could use a custom comparator function, as described in https://wiki.python.org/moin/HowTo/Sorting#The_Old_Way_Using_the_cmp_Parameter.

Or you can use a key function (by passing the key keyword argument to list.sort) to transform the value being sorted to a different one:

>>> ls = ['qa','uat','prod','dev']
>>> ls.sort(key=lambda x: (1,x) if x=='dev' else (0,x))
>>> ls
['prod', 'qa', 'uat', 'dev']
>>>

or do the same thing with a function:

>>> def my_key_func(x):
...     if x=='dev':
...         return (1,x)
...     else:
...         return (0,x)
...
>>> ls.sort(key=my_key_func)
>>> ls
['prod', 'qa', 'uat', 'dev']
>>>
fferri
  • 18,285
  • 5
  • 46
  • 95
  • Thank a lot for your answer, it solved my problem. As i am new to python can you please explain to me how this sort worked. – Amit Mallick Apr 24 '15 at 19:49
  • `my_key_func` will transform strings to tuples: `[(0,'qa'), (0,'uat'), (0,'prod'), (1,'dev')]`, such that when sorting using natural order, first they will be compared by the first numeric element, and if that is equal, they will be compared by the second element, which is a string, and strings are naturally sorted alphabetically. `'dev'` goes to the end of list because it has an higher first numeric element. – fferri Apr 24 '15 at 19:55
  • if you want to know more, read https://wiki.python.org/moin/HowTo/Sorting – fferri Apr 24 '15 at 19:58