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

I have a list of integers in a 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 an integer, for example:

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

Finally, I will sort it as shown 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 ?

+4
source share
3 answers

You can do this in one step:

 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] >>> 
+19
source
 >>> L1 = ['11', '10', '13', '12', '15', '14', '1', '3', '2', '5', '4', '7', '6', '9', '8'] >>> L1 = [int(x) for x in L1] >>> L1 [11, 10, 13, 12, 15, 14, 1, 3, 2, 5, 4, 7, 6, 9, 8] >>> L1.sort() >>> L1 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] >>> L3 = L1 
+5
source
 L3 = sorted(int(x) for x in L1) 
+4
source

Source: https://habr.com/ru/post/1307747/


All Articles