且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将空格和逗号分隔的数字字符串转换为 int 列表?

更新时间:2023-09-06 19:59:22

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

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

或者使用列表推导式:

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

如果您想要列表结果,后者效果更好,或者您可以将 map() 调用包装在 list() 中.

这是可行的,因为 int() 容忍空格:

>>>example_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'>>>list(map(int, example_string.split(','))) # Python 3,在 Python 2 中 list() 调用是多余的[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]

分割只是一个逗号也更能容忍变量输入;值之间使用 0、1 或 10 个空格都没有关系.

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?

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 if you want a list result, or you can wrap the map() call in list().

This works because int() tolerates whitespace:

>>> example_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'
>>> list(map(int, example_string.split(',')))  # Python 3, in Python 2 the list() call is redundant
[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 just a comma also is more tolerant of variable input; it doesn't matter if 0, 1 or 10 spaces are used between values.