Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python—将一个数字字符串转换为一个整数列表_Python_String_List_Integer - Fatal编程技术网

Python—将一个数字字符串转换为一个整数列表

Python—将一个数字字符串转换为一个整数列表,python,string,list,integer,Python,String,List,Integer,我有一串数字,比如: example_string = '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])) 我想将其转换为一个列表: example_list = [0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 1

我有一串数字,比如:

example_string = '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]))
我想将其转换为一个列表:

example_list = [0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11]
我试过这样的方法:

example_string = '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, 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]
仅使用逗号进行拆分也更能容忍变量输入;在值之间使用0、1或10个空格并不重要。

应该可以

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(',')]

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

[ int(x) for x in example_string.split(',') ]
试试这个:

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

我想最肮脏的解决办法是:

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

example_string.split(',')
Hey Rohit:)。欢迎来到SO。您介意在代码中添加一些解释吗?因此,下一位与会者对您的答案有了更好的了解:)。如果原始数字字符串以“python格式”存储,则此解决方案实际上将适应存储的任何类型的数据0,0,0,11'将映射到int类型,“0.12,0.1,1.2”将映射到float类型,而无需显式编码。它可能更脏,但脏到足以赢得我的否决票。为什么还要发布这样一个可怕的解决方案呢?对于python3,你必须将
map(int,example\u string.split(','))
更改为
list(map(int,example\u string.split(','))
@Tengerye:这取决于;如果您只需要一个iterable,那么
map()
对象就可以了。非常感谢!!!!