本文介绍了Python - 将一串数字转换为int列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一串数字,例如:
example_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'
我想将此转换为列表:
example_list = [0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11]
我在示例字符串中尝试了类似
I tried something like
for i in example string:
example_list.append(int(example_string[i]))
但这显然不起作用,因为字符串包含空间和昏迷。但是,删除它们不是一种选择,因为像19这样的数字会转换为1和9.你能帮我解决这个问题吗?
but this obviously does not work as the string contains spaces and comas. However, removing them is not an option, as numbers like '19' would be converted to 1 and 9. Could you please help me with this?
推荐答案
在逗号上拆分,然后映射到整数:
Split on commas, then map to integers:
map(int, example_string.split(','))
或使用列表理解:
[int(s) for s in example_string.split(',')]
如果你想要一个列表结果,后者在Python 3上效果更好。
The latter works better on Python 3 if you want a list result.
这是因为 int()
容忍空格:
>>> example_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'
>>> map(int, example_string.split(','))
[0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11]
>>> [int(s) for s in example_string.split(',')]
[0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11]
分裂只是 a逗号也更容忍变量输入;如果值之间使用0,1或10个空格并不重要。
Splitting on just a comma also is more tolerant of variable input; it doesn't matter if 0, 1 or 10 spaces are used between values.
这篇关于Python - 将一串数字转换为int列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!