如何将空格和逗号分隔的数字字符串转换为 int 列表? [英] How to convert a string of space- and comma- separated numbers into a list of int?

查看:87
本文介绍了如何将空格和逗号分隔的数字字符串转换为 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]

我尝试了类似的东西:

for i in example_string:example_list.append(int(example_string[i]))

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

解决方案

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

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.

这篇关于如何将空格和逗号分隔的数字字符串转换为 int 列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆