使用Python中的变量定义创建字符串(对于nympy.arange对象)
我正在编写一个Python脚本,我想生成一个包含变量定义的字符串,它是一个numpy数组。我希望将其写入外部文件或屏幕,而不是打印/写入整个阵列 为了说明这一点,我有:使用Python中的变量定义创建字符串(对于nympy.arange对象),python,arrays,string,numpy,Python,Arrays,String,Numpy,我正在编写一个Python脚本,我想生成一个包含变量定义的字符串,它是一个numpy数组。我希望将其写入外部文件或屏幕,而不是打印/写入整个阵列 为了说明这一点,我有: import numpy as np normalization = np.arange(4, 11, 0.1) 我想获得: normalization_string = 'np.arange(4, 11, 0.1)' 无需手动写入,但指定当然要从变量规范化生成字符串 有没有一种简单的方法来生成该字符串?一般来说,您不能,因
import numpy as np
normalization = np.arange(4, 11, 0.1)
我想获得:
normalization_string = 'np.arange(4, 11, 0.1)'
无需手动写入,但指定当然要从变量规范化
生成字符串
有没有一种简单的方法来生成该字符串?一般来说,您不能,因为变量根本不知道(因为变量不关心)它是如何创建的 例如,在你的例子中,
np.arange
只是一个函数。它返回一个np.ndarray
,但是有几种方法可以创建numpy.ndarray
:
>>> import numpy as np
>>> np.arange(4, 5, 0.1)
array([ 4. , 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 4.9])
>>> np.arange(40, 50) / 10.
array([ 4. , 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 4.9])
>>> np.array(range(40, 50, 1)) / 10.
array([ 4. , 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 4.9])
>>> np.linspace(4, 4.9, 10)
array([ 4. , 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 4.9])
它们都创建相同的数组
我的忠告是: 仅保护在运行之间更改的参数,例如,如果要修改“步骤”: 如果启动、停止和步骤不同:
start = 4
stop = 11
step = 0.1
arr = np.arange(start, stop, step)
# do something with arr
res = ... # the result
# safe "start", "stop", "step" and "res".
print('np.arange({}, {}, {})'.format(start, stop, step)) # or create the string
我添加了
打印
s,主要是因为您明确要求使用字符串表示。我想我找到了一个解决方法:
使用委托所有变量定义的特定类,例如:
class VariableConstructor():
def __init__(self):
self.idsTable = []
def construct_primitive(self, value):
x = value
self.idsTable.append( (id(x), type(value), str(value)) )
return x
def construct_object(self, constructor, args=None, kwargs=None):
if args is not None and kwargs is not None:
x = constructor(*args, **kwargs)
self.idsTable.append( (id(x), constructor, str(args) + ',' + str(kwargs)) )
elif args is not None:
x = constructor(*args)
self.idsTable.append( (id(x), constructor, str(args)) )
elif kwargs is not None:
self.idsTable.append( (id(x), constructor, str(kwargs)) )
x = constructor(**kwargs)
else:
x = constructor()
self.idsTable.append( (id(x), constructor, '') )
return x
def get_string_representation(self, variable):
_, t, args = filter(lambda x: x[0] == id(variable), self.idsTable)[0]
return str(t).replace('<','').replace('>','')+':'+args
这将输出:
type 'int':5
type 'float':10.0
type 'list':
built-in function arange:(4, 11, 0.1)
一些注释:-这是一个示例代码,bug可能潜伏在任何地方。
-您可以轻松地更改变量字符串在
get\u string\u representation()
方法中的显示方式。-您的代码可能很难从其他人处读取 EDIT:我误读了你的话,认为你需要一个通用的变量方法。没有看到它只是用于
np.arange
对象。这是一种矫枉过正的做法。(恰当的答案是在评论中)
但是,我想我会把我的答案留在这里,因为它回答了问题的标题。简单地回答:不,不要尝试这样做。无论您试图解决什么问题:可能有一种更好、更简单的方法。问题是每次运行脚本时,我都以不同的方式在脚本中定义一些变量(例如,np.arange的不同数字),我希望脚本将这些变量保存在外部文件中,但要以人类可读的方式(为了在末尾比较不同的输出文件)。您有什么建议?定义“开始”-参数:即
start,stop,step=4,11,0.1
,然后创建数组:np.arange(start,stop,step)
然后安全地开始
,停止
和步骤
以及您的任何输出。谢谢,我不知道我怎么会没有意识到。。。
import numpy as np
vc = VariableConstructor()
i = vc.construct_primitive(5)
f = vc.construct_primitive(10.)
l = vc.construct_object(list)
arr = vc.construct_object(np.arange, (4,11,0.1))
print(vc.get_string_representation(i))
print(vc.get_string_representation(f))
print(vc.get_string_representation(l))
print(vc.get_string_representation(arr))
type 'int':5
type 'float':10.0
type 'list':
built-in function arange:(4, 11, 0.1)