简体   繁体   English

将字符串格式的数学等式转换为可在Python3中使用的数学等式

[英]Convert a math equation in string format to something workable in Python3

So I have a function that takes a math equation in string format, and a list of numbers. 所以我有一个函数,它采用字符串格式的数学方程式和数字列表。

The purpose of the function is to apply that function to each number (an exponent function), and return the result. 该函数的目的是将该函数应用于每个数字(指数函数),并返回结果。

For example, I am trying to pass "x**4" to it, and the list [4,3,2] 例如,我试图将“x ** 4”传递给它,列表[4,3,2]

The end result, of course, would be [256, 81, 16] 最终的结果当然是[256,81,16]

How do you convert the string to a math equation while also keeping in mind that the string could be anything from "x* 2" or "x *3". 如何将字符串转换为数学方程,同时还要记住字符串可以是“x * 2”或“x * 3”中的任何内容。

Use the eval function , and use a list comprehension. 使用eval函数 ,并使用列表推导。 This requires you know the var name ahead of time. 这要求您提前知道var名称。 If you don't, parse it then use this. 如果不这样做,请解析它,然后使用它。

>>> operation = "x**4"
>>> num_list = [4,3,2]
>>> [eval(operation) for x in num_list]
[256, 81, 16]

Depends how complicated you need it to be. 取决于你需要它有多复杂。 Could you use the map builtin like: 你可以使用内置的地图:

x = [4, 3, 2]

def exp4( val ):
    return val ** 4

map( exp4, x )

You define the functions you need and apply them as an when. 您可以定义所需的功能并将其作为时间应用。 You've not said if you need an abilty to pick functions dynamically and it presumes an itterable (list in this case). 你没有说过你是否需要一个能够动态选择函数的能力而且它假定一个可以移动的(在这种情况下是列表)。

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

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