python - Sort criteria - sorted() -
i'd sort list following 2 criteria in order:
- numerical order; then
- alphabetical order.
i'm using:
from re import search my_list = ['nelsonfreire87956423', 'martha34685128', 'gleen34685128', 'polini13452678'] first_sort = sorted(my_list, key=lambda x: [x]) sorted_list = sorted( first_sort, key=lambda x: search(r'\d{8}', x).group() if search(r'\d{8}', x) else [] ) print(sorted_list)
which gives desired result:
['polini13452678', 'gleen34685128', 'martha34685128', 'nelsonfreire87956423']
i'd know how can sort list one sorted
call. mean, how can pass multiple criteria sorted
?
your key
function can return a tuple, elements @ each position in tuple used break ties elements @ previous position. example:
def my_key(s): name, num = search(r'(\d+)(\d+)', s).groups() return int(num), name
which results in:
>>> my_key('nelsonfreire87956423') (87956423, 'nelsonfreire') # i.e. sort on number first, name
and therefore:
>>> sorted(my_list, key=my_key) ['polini13452678', 'gleen34685128', 'martha34685128', 'nelsonfreire87956423']
Comments
Post a Comment