如何对它们之间有空格的列表进行排序

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


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)


慕娘9325324
浏览 298回答 3
3回答

ITMISS

中的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()&nbsp; # .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)&nbsp; # 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]

明月笑刀无情

从用户那里获取带有空格的输入:strength&nbsp;=&nbsp;list(map(int,&nbsp;input().strip().split()))对它们进行排序:strength.sort()并打印:print(strength)

慕码人8056858

首先,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]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python