How to sort a list with user defined condition in python? -
i new python.i want sort list condition. ex:
i getting environment details , storing them list below. ls = ['qa','uat','prod','dev']
can order. ls = ['uat','qa','dev','prod']
but result list should be:
rls = ['prod','qa','uat','dev']
you use custom comparator function, described in https://wiki.python.org/moin/howto/sorting#the_old_way_using_the_cmp_parameter.
or can use key function (by passing key
keyword argument list.sort) transform value being sorted 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 same thing 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'] >>>
Comments
Post a Comment