1
list = ['c:8', 'c:9', 'c:13', 'c:19', 'c:2', 'c:3', 'c:0', 'c:1', 'c:6', 'c:7', 'c:4', 'c:5', 'c:14', 'c:18', 'c:17', 'c:12', 'c:15', 'c:11', 'c:10', 'c:16', 'c:20']

I used "sorted()" but get this result

['c:0', 'c:1', 'c:10', 'c:11', 'c:12', 'c:13', 'c:14', 'c:15', 'c:16', 'c:17', 'c:18', 'c:19', 'c:2', 'c:20', 'c:3', 'c:4', 'c:5', 'c:6', 'c:7', 'c:8', 'c:9']

But what I want is

['c:0', 'c:1', 'c:2', 'c:3', 'c:4', 'c:5', 'c:6', 'c:7', 'c:8', 'c:9', 'c:10', 'c:11', 'c:12', 'c:13', 'c:14', 'c:15', 'c:16', 'c:17', 'c:18', 'c:19','c:20']

Besides getting what I want, I want why sorted() could not work.

Jack
  • 1,724
  • 4
  • 18
  • 33

3 Answers3

2
>>> l = ['c:8', 'c:9', 'c:13', 'c:19', 'c:2', 'c:3', 'c:0', 'c:1', 'c:6', 'c:7', 'c:4', 'c:5', 'c:14', 'c:18', 'c:17', 'c:12', 'c:15', 'c:11', 'c:10', 'c:16', 'c:20']
>>> l.sort(key=lambda x: int(x[2:])
>>> l
['c:0', 'c:1', 'c:2', 'c:3', 'c:4', 'c:5', 'c:6', 'c:7', 'c:8', 'c:9', 'c:10', 'c:11', 'c:12', 'c:13', 'c:14', 'c:15', 'c:16', 'c:17', 'c:18', 'c:19', 'c:20']

Because 'c:1', 'c:10', 'c:11' are string, and 'c:1', 'c:10', 'c:11' are all start with c:1. So you get something like 'c:1', 'c:10', 'c:11', 'c:12', 'c:13', 'c:14'.

As my code, use key argument of sorted() or list.sort(), and use slice to get the number, then use int() function covert the number into int.

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
1

use sorted with lambda such that sort on the number in string.

sorted(list, key=lambda x:int(x.split(':')[-1]))

['c:0',
 'c:1',
 'c:2',
 'c:3',
 'c:4',
 'c:5',
 'c:6',
 'c:7',
 'c:8',
 'c:9',
 'c:10',
 'c:11',
 'c:12',
 'c:13',
 'c:14',
 'c:15',
 'c:16',
 'c:17',
 'c:18',
 'c:19',
 'c:20']
Vishnu Upadhyay
  • 5,043
  • 1
  • 13
  • 24
1

You need lambda function as key for sorting to split each element and convert second part to integer:

l = sorted(l, key=lambda x: int(x.split(':')[1]))

Also you should rename list variable, because it is reserved name in python.

Eugene Soldatov
  • 9,755
  • 2
  • 35
  • 43