一个字符串,再一个数组的presentation转换为在python实际阵列 [英] Converting a string representation of an array to an actual array in python

查看:89
本文介绍了一个字符串,再一个数组的presentation转换为在python实际阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

喜做在网络上的一些东西,不知道是否有转换的python数组作为一个字符串返回到Python阵列..例如任何方式

Hi doing some stuff over a network and wondering if there is any way of converting python array as a string back into a python array.. for example

x = "[1,2,3,4]"

将X为

x_array = [1,2,3,4]

奖金,如果它也可以为numpy的多维数组工作!

Bonus if it can also work for numpy multidimensional arrays!

推荐答案

有关正常的阵列,使用的 ast.literal_eval

For the normal arrays, use ast.literal_eval:

>>> from ast import literal_eval
>>> x = "[1,2,3,4]"
>>> literal_eval(x)
[1, 2, 3, 4]
>>> type(literal_eval(x))
<type 'list'>
>>>

numpy.array 虽然是因为Python如何使它们为字符串有点棘手:

numpy.array's though are a little tricky because of how Python renders them as strings:

>>> import numpy as np
>>> x = [[1,2,3], [4,5,6]]
>>> x = np.array(x)
>>> x
array([[1, 2, 3],
       [4, 5, 6]])
>>> x = str(x)
>>> x
'[[1 2 3]\n [4 5 6]]'
>>>

您可以使用虽然简单的人一个黑客正在使用的 应用re.sub

One hack you could use though for simple ones is replacing the whitespace with commas using re.sub:

>>> import re
>>> x = re.sub("\s+", ",", x)
>>> x
'[[1,2,3],[4,5,6]]'
>>>

然后,您可以使用 ast.literal_eval ,把它放回一个 numpy.array

>>> x = literal_eval(x)
>>> np.array(x)
array([[1, 2, 3],
       [4, 5, 6]])
>>>

这篇关于一个字符串,再一个数组的presentation转换为在python实际阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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