简体   繁体   中英

Sort list of list of String numbers in Python3?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM