2017-06-11 5 views
2

私はPythonスクリプトで作業しています。変数の定義を持つ文字列をnumpy配列として生成したいと考えています。私はこれを外部ファイルに書き込むか、配列全体を印刷/書き込みする代わりに画面に書きたいと思っています。(nympy.arangeオブジェクトの)Pythonで変数定義付きの文字列を作成する

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

と私は取得したいと思います:

はそれを明確にするために、私が持っている

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

手動でそれを記述することなく、もちろん指定することから文字列を生成します変数normalization

文字列を生成する簡単な方法はありますか?

+2

単に答えてください。しないようにしてください。あなたがこれで解決しようとする問題は何でも:おそらくはるかに簡単で簡単です。 – MSeifert

+0

問題は、私がスクリプトを実行するたびに、スクリプト内のいくつかの変数を異なる方法( 'np.arange'とは異なる数)で定義し、これらの変数を外部ファイルに保存したいのですが、 (最終的に異なる出力ファイルを比較するために)人間が読める形式です。何をお勧めしますか? –

+1

'start、stop、step = 4、11、0.1'を定義し、' np.arange(start、stop、step) 'という配列を作成し、' start'、あなたが持っているどんな出力であれ、「止める」と「ステップ」と。 – MSeifert

答えて

3

一般に、変数が作成された方法を(変数は気にしないので)知りません。

たとえば、あなたのケースではnp.arangeは機能に過ぎません。それらのすべてが同じ配列を作成

>>> 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]) 

:しかしnumpy.ndarrayを作成するには、いくつかの方法があり、np.ndarray返します。


私のアドバイス:あなたは「ステップ」を変更したい場合は、たとえば、実行の間に変更

念あなたのパラメーター:

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 

あなたが明示的に文字列を求めたので、私はほとんどprint秒を追加しました表現。

私は回避策を見つけたと思う
0

:それから、これはいくつかのサンプルコードです

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()メソッドの中にどのように入れるかを簡単に変更できます。
- あなたのコードは他人から読み取るのが難しい場合があります。

EDIT:あなたが言ったことを誤って読んで、どの変数でも一般的な方法が必要だと思った。それはちょうどnp.arangeオブジェクトのためであったか分からなかった。これは過剰です。(適切な答えはコメントにありました)

しかし、私は質問のタイトルに答えるのでここで私の答えを残すと思います。

関連する問題