简体   繁体   中英

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 ?

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]
>>>
>>> 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
L3 = sorted(int(x) for x in L1)

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