为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕娘9325324 2022-01-18 17:21:42
我正在尝试对带有空格的列表进行排序,例如,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)
查看完整描述

3 回答

?
ITMISS

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]


查看完整回答
反对 回复 2022-01-18
?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

从用户那里获取带有空格的输入:

strength = list(map(int, input().strip().split()))

对它们进行排序:

strength.sort()

并打印:

print(strength)


查看完整回答
反对 回复 2022-01-18
?
慕码人8056858

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]


查看完整回答
反对 回复 2022-01-18
  • 3 回答
  • 0 关注
  • 297 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号