Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a list of strings [ '3', '1', '2' ] to a list of sorted integers [1, 2, 3]

I have a list of integers in string representation, similar to the following:

L1 = ['11', '10', '13', '12', 
      '15', '14',  '1',  '3', 
       '2',  '5',  '4',  '7', 
       '6', '9', '8']

I need to make it a list of integers like:

L2 = [11, 10, 13, 12, 15, 14, 1, 3, 2, 5, 4, 7, 6, 9, 8]

Finally I will sort it like below:

L3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] # by L2.sort()

Please let me know what is the best way to get from L1 to L3?

like image 761
Shamim Avatar asked Nov 27 '22 15:11

Shamim


1 Answers

You could do it in one step like this:

L3 = sorted(map(int, L1))

In more detail, here are the steps:

>>> L1 = ['11', '10', '13', '12', '15', '14', '1', '3', '2', '5', '4', '7', '6', '9', '8']
>>> L1
['11', '10', '13', '12', '15', '14', '1', '3', '2', '5', '4', '7', '6', '9', '8']
>>> map(int, L1)
[11, 10, 13, 12, 15, 14, 1, 3, 2, 5, 4, 7, 6, 9, 8]
>>> sorted(_)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
>>>
like image 180
Greg Hewgill Avatar answered Nov 30 '22 03:11

Greg Hewgill