【问题标题】:Create a string with a variable definition in Python (of a nympy.arange object)在 Python 中创建一个带有变量定义的字符串(一个 numpy.arange 对象)
【发布时间】:2017-06-11 14:21:34
【问题描述】:

我正在编写一个 Python 脚本,我想生成一个带有变量定义的字符串,该变量是一个 numpy 数组。我希望将其写入外部文件或屏幕,而不是打印/写入整个数组。

为了清楚起见,我有:

import numpy as np
normalization = np.arange(4, 11, 0.1)

我想获得:

normalization_string = 'np.arange(4, 11, 0.1)'

无需手动编写,当然要指定从变量normalization生成字符串。

有没有一种简单的方法来生成那个字符串?

【问题讨论】:

  • 简单回答:不,不要尝试这样做。无论您试图用这个解决什么问题:可能有一种更好、更简单的方法。
  • 问题是我在脚本中以不同的方式定义了一些变量(比如 np.arange 的不同数字),我希望脚本将这些变量保存在外部文件,但以人类可读的方式(为了在最后比较不同的输出文件)。你有什么建议?
  • 定义你的“开始”参数:即start, stop, step = 4, 11, 0.1,然后创建数组:np.arange(start, stop, step),然后只是安全的startstopstep以及任何你有的输出。
  • 谢谢,我不知道我怎么没意识到...

标签: python arrays string numpy


【解决方案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])

它们都创建相同的数组。


我的建议:

只需保护在运行之间更改的参数,例如,如果您想修改“步骤”:

step = 0.1

arr = np.arange(4, 11, step)
# do something with arr

res = ... # the result

# safe only the "step" and "res".
print('np.arange(4, 11, {})'.format(step))  # creating a string

如果开始、停止和步进不同:

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

我添加 prints 主要是因为您明确要求字符串表示。

【讨论】:

    【解决方案2】:

    我想我找到了解决方法:

    使用委托所有变量定义的特定类,例如:

    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
    

    那么,这是一些示例代码:

    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)
    

    一些注意事项:
    - 这是一个示例代码,错误可能潜伏在任何地方。
    - 您可以轻松更改变量字符串在 get_string_representation() 方法中的显示方式。
    - 您的代码可能很难从其他人那里阅读。

    编辑:我误读了您所说的内容,并认为您希望为任何变量提供通用方法。没有看到它只是针对np.arange 对象。这是一个矫枉过正。(适当的答案是在 cmets)

    但是,我想我会在这里留下我的答案,因为它回答了问题的标题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-28
      • 1970-01-01
      • 1970-01-01
      • 2013-03-05
      • 1970-01-01
      • 2020-08-11
      • 2015-10-14
      相关资源
      最近更新 更多