简体   繁体   English

如何运行打印的代码Python

[英]How to run printed code Python

I am trying to create a function that runs printed code. 我正在尝试创建一个运行打印代码的函数。 For example, 例如,

def test(mylist):
    mydict = {}
    for i in range(mylist):
        mydict[i] = ('x'+'%s' %i)
        print ("%s = %s" %(mydict[i], i))
test(3)

Output: 输出:

x0 = 0
x1 = 1
x2 = 2

I basically want my function to run these printed commands and set x0=0 , x1=1 , and so on. 我基本上希望我的函数运行这些打印的命令并设置x0=0x1=1等。 I could not think of a way to do it. 我想不出办法。 Thanks! 谢谢!

Edit: 编辑:

I edited the code based on your dictionary idea. 我根据您的字典构想编辑了代码。 But, it does not still seem to be helping to solve for the gradient of a given function. 但是,它似乎仍无助于解决给定函数的梯度。 Can you please help me on this? 你能帮我吗?

import sympy as sy
def test(mylist):
    d = {}
    for i in range(mylist):
        d['x'+str(i)] = 'sy.symbols(x%s, real=True)' %i
    return d
test(3)

f = (1/3*x0**6 - 2.1*x0**4 + 4*x0**2 + 
            x0*x1 - 4*x1**2 + 4*x1**4 + x2)
gf = [sy.diff(f, x0), sy.diff(f, x1), sy.diff(f, x2)]
gf

As pointed out in comments, dictionaries are the way to go. 正如评论中指出的那样,词典是必经之路。 Stylistically, get in the habit of using return rather than printing results. 从风格上讲,养成使用return而不是打印结果的习惯。

I've made some changes to your code, which should illustrate these points: 我对您的代码进行了一些更改,这些代码应说明以下几点:

def test(mylist):
    d = {}
    for i in range(mylist):
        d['x'+str(i)] = i
    return d

test(3)  # {'x0': 0, 'x1': 1, 'x2': 2}

Trying to create dynamic variables is almost always a bad idea. 尝试创建动态变量几乎总是一个坏主意。 It's dangers and often unnecessarily pollutes a namespace. 这是危险,通常会不必要地污染名称空间。 However, I agree that just using plain variables here would be easier. 但是,我同意仅在此处使用普通变量会更容易。 Thus, you can return a list of values from test , and unpack them into three variables ( x0 , x1 , and x2 ): 因此,您可以返回test的值列表,并将它们解压缩为三个变量( x0x1x2 ):

Create a list of your values: 创建一个值列表:

def test(mylist):
    return [sy.symbols('x' + str(n), real=True) for n in range(mylist)]

And then create your gf list using the values in the list: 然后使用列表中的值创建gf列表:

x0, x1, x2 = test(3)
f = (1/3*x0**6 - 2.1*x0**4 + 4*x0**2 + x0*x1 - 4*x1**2 + 4*x1**4 + x2)
gf = [sy.diff(f, x0), sy.diff(f, x1), sy.diff(f, x2)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM