首页 > 解决方案 > 如何对它们之间有空格的列表进行排序

问题描述

我正在尝试对带有空格的列表进行排序,例如,

my_list = [20 10 50 400 100 500]

但我有一个错误

"ValueError: invalid literal for int() with base 10: '10 20 50 100 500 400 '"

代码:

strength = int(input())
strength_s = strength.sort()
print(strength_s)

标签: pythonpython-3.x

解决方案


中的input函数python将整行作为str.
因此,如果您输入一个以空格分隔的整数列表,该input函数会将整行作为字符串返回。

>>> a = input()
1 2 3 4 5

>>> type(a)
<class 'str'>

>>> a
'1 2 3 4 5'

如果要将其保存为整数列表,则必须遵循以下过程。

>>> a = input()
1 2 3 4 5
>>> a
'1 2 3 4 5'

现在,我们需要将字符串中的数字分开,即拆分字符串。

>>> a = a.strip().split()  # .strip() will simply get rid of trailing whitespaces
>>> a
['1', '2', '3', '4', '5']

我们现在有了 a listof strings,我们必须将它转换为 a listof ints。我们必须调用int()的每个元素,list最好的方法是使用map函数。

>>> a = map(int, a)
>>> a
<map object at 0x0081B510>
>>> a = list(a)  # map() returns a map object which is a generator, it has to be converted to a list
>>> a
[1, 2, 3, 4, 5]

我们终于有list一个ints

整个过程主要在一行python代码中完成:

>>> a = list(map(int, input().strip().split()))
1 2 3 4 5 6
>>> a
[1, 2, 3, 4, 5, 6]

推荐阅读