test_list = [['10','fff'], ['11','dfhg'], ['3','zszszs'], ['4','ll'], ['18','kds']]
test_list.sort()
for line in test_list:
print(line)
This code sorts the list like this:
['10', 'fff']
['11', 'dfhg']
['18', 'kds']
['3', 'zszszs']
['4', 'll']
But I need to sort it in numeric order like this:
['3', 'zszszs']
['4', 'll']
['10', 'fff']
['11', 'dfhg']
['18', 'kds']
I have already tried the .sorted()
function and itemgetter
, none of these works.
Using the key argument for sort, will give a customized sort
test_list = [['10','fff'], ['11','dfhg'], ['3','zszszs'], ['4','ll'], ['18','kds']]
test_list.sort(key=lambda x: int(x[0]))
for line in test_list:
print(line)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.