将字符串列表['3','1','2']转换为有序整数列表[1,2,3]

时间:2010-04-23 00:40:34

标签: python string list sorting integer

我在字符串表示中有一个整数列表,类似于以下内容:

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

我需要把它作为一个整数列表,如:

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

最后,我将按如下方式对其进行排序:

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

请告诉我从L1L3的最佳方式是什么?

3 个答案:

答案 0 :(得分:19)

你可以像这样一步完成:

L3 = sorted(map(int, L1))

更详细地说,以下是步骤:

>>> 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]
>>>

答案 1 :(得分:5)

>>> 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

答案 2 :(得分:4)

L3 = sorted(int(x) for x in L1)