简体   繁体   English

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

[英]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 ? 请告诉我从L1L3的最佳方式是什么?

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM