开发者

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]

开发者_JS百科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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜