python - 如何对它们之间有空格的列表进行排序
问题描述
我正在尝试对带有空格的列表进行排序,例如,
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)
解决方案
中的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 list
of strings
,我们必须将它转换为 a list
of 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]
推荐阅读
- c - 在 C 中实现按位运算
- java - 在 Java 中使用正则表达式替换第 n 个字符
- apache-kafka - 找不到 lz4 压缩编解码器的库 - kafka python
- javascript - 如何为给定的 vue3 模板生成渲染函数?
- algorithm - 最坏情况等于最佳情况算法
- java - 使用 javax.measure 进行 NONSI 和 SI 单位转换的合适包和 maven 存储库
- android - 如何在不使用 init 的情况下从类中启动协程?
- cron - NestJS Cron 作业导入无服务注入
- jquery - 模态按钮不适用于事件点击?
- rust - Prost - 不能在 trait 对象上调用`encode` 方法