3 回答

TA贡献1871条经验 获得超8个赞
中的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]

TA贡献1828条经验 获得超4个赞
从用户那里获取带有空格的输入:
strength = list(map(int, input().strip().split()))
对它们进行排序:
strength.sort()
并打印:
print(strength)

TA贡献1803条经验 获得超6个赞
首先,my_list = [20 10 50 400 100 500]它既不是列表,也不是表示列表的正确方式。您使用 代表一个列表my_list = [20, 10 ,50, 400, 100, 500]。
我会假设my_list是一个字符串。因此,您将字符串拆分为列表,将列表转换为整数,然后对其进行排序,如下所示
my_list = "20 10 50 400 100 500"
li = [int(item) for item in my_list.split(' ')]
print(sorted(li))
#[10, 20, 50, 100, 400, 500]
为了使您的原始代码工作,我们会做
strength = input()
strength_li = [int(item) for item in strength.split(' ')]
print(sorted(strength_li))
输出看起来像。
10 20 40 30 60
#[10, 20, 30, 40, 60]
添加回答
举报