Python - 将一串数字转换为一个 int 列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19334374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:29:16  来源:igfitidea点击:

Python - converting a string of numbers into a list of int

pythonstringlistinteger

提问by Bart M

I have a string of numbers, something like:

我有一串数字,例如:

example_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'

I would like to convert this into a list:

我想将其转换为列表:

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]))

But this obviously does not work, as the string contains spaces and commas. 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?

但这显然不起作用,因为字符串包含空格和逗号。但是,删除它们不是一种选择,因为像“19”这样的数字会被转换为 1 和 9。你能帮我解决这个问题吗?

回答by Martijn Pieters

Split on commas, then map to integers:

用逗号分割,然后映射到整数:

map(int, example_string.split(','))

Or use a list comprehension:

或者使用列表理解:

[int(s) for s in example_string.split(',')]

The latter works better on Python 3 if you want a list result.

如果您想要列表结果,后者在 Python 3 上效果更好。

This works because int()tolerates whitespace:

这是有效的,因为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(','))  # Python 2, in Python 3 returns iterator object
[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]

Splitting on justa comma also is more tolerant of variable input; it doesn't matter if 0, 1 or 10 spaces are used between values.

在逗号上拆分也更能容忍变量输入;值之间是否使用 0、1 或 10 个空格都没有关系。

回答by lucemia

it should work

它应该工作

example_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'
example_list = [int(k) for k in example_string.split(',')]

回答by lejlot

You can also use list comprehension on splitted string

您还可以对拆分的字符串使用列表理解

[ int(x) for x in example_string.split(',') ]

回答by Charles JOUBERT

Try this :

尝试这个 :

import re
[int(s) for s in re.split('[\s,]+',example_string)]

回答by hendrik

I guess the dirtiest solution is this:

我想最肮脏的解决方案是这样的:

list(eval('0, 0, 0, 11, 0, 0, 0, 11'))

回答by Rohit Singh

number_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'

number_string = number_string.split(',')

number_string = [int(i) for i in number_string]