How to sort a list with lambda in Python

2 Answers

0 votes
lst = ['a10', 'a01', 'a12', 'a02', 'a20', 'a03']

# x: int(x[1:] = ignore the first character 
lst = sorted(lst, key=lambda x: int(x[1:]))
 
print(lst)
 
 
 

 
'''
run:
 
['a01', 'a02', 'a03', 'a10', 'a12', 'a20']
 
'''

 



answered Apr 28, 2021 by avibootz
edited Apr 28, 2021 by avibootz
0 votes
lst = ['10', '01', '12', '02', '03', '20']

# x: int(x[1:] = ignore the first character
lst = sorted(lst, key=lambda x: int(x[1:]))

print(lst)




'''
run:

['10', '20', '01', '12', '02', '03']

'''

 



answered Apr 28, 2021 by avibootz
...