将包含 '[' 和 ']' 的字符串数组转换为整数数组

3

我正在尝试使用以下方式将字符串数组转换为浮点数数组:

arr_str = '[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]'

a1 = arr_str.split()

[int(x) for x in a1]

但是会抛出错误:
<
ipython-input-57-f7f1eaba7ebd> in <listcomp>(.0)
      3 a1 = arr_str.split()
      4 
----> 5 [int(x) for x in a1]
      6 
      7 # for a in arr_str.split():

ValueError: invalid literal for int() with base 10: '[1'

应该对字符串进行预处理并删除 '[' 和 ']' 吗?

你能在 [ 和第一个 1 之间加一个空格吗?这样你的列表推导式看起来就像:[int(x) for x in a1[1:-1]。预处理字符串以删除 [] 也可以起到同样的效果。 - ChootsMagoots
使用 arr_str.strip('[]').split() - user8190410
3个回答

3
一种方法是使用ast.literal_eval
如果你需要一个numpy整数数组,转换是很简单的。
import numpy as np
from ast import literal_eval

arr_str = '[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]'

res = literal_eval(arr_str.replace(' ', ','))

# [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

res_np = np.array(res)

# array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])

0
arr_str = arr_str.strip("[]")
voila = [int(x) for x in arr_str.split()]

编辑1:对变量赋值要求严谨。


谢谢朋友。根据OP的字符串和Python2.7.8,我的strip语句完全正常。 - W4t3randWind

0
你可以使用 ast 模块:
import ast

arr_str = '[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]'

arr = ast.literal_eval(arr_str.replace(" ",", "))
arr = list(map(float,arr)) #Remove this line if you wish integer conversion.
print(arr)

输出:

[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]

由于您在标题中提到了int,但在描述中提到了float


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接