如何将用户输入以变量形式传递给 python 中的 lambda 函数?

How can I pass user input in the form of a variable to a lambda function in python?

所以我对编程有点陌生,我正在寻找一些帮助。我正在制作一个图形计算器,并希望用户使用 x 输入方程式,例如 (x + 3) 或 (x^2 + 3x + 4)。我最近发现了 lambda 函数,想知道是否有一种方法可以将变量传递给它,以便使用用户的方程式获取绘图点。我计划使用 for 循环来不断将新值传递到等式中。如果您对如何完成我的图形计算器有任何其他建议,请随时告诉我。到目前为止,我的代码只是用户浏览我的程序的一种方式。这是我的代码:

def main():
    while True:
        response = menu()
        if response == "1":
            print("enter an equation in the form of mx + b")
            equation = (input())
            print(coordinates(equation))
        elif response == "2":
            print("enter a value for x")
            x = input()
            print("enter a value for y")
            y = input()
        elif response == "0":
            print("Goodbye")
            break
        else:
            print("please enter '1' '2' or '0'")

def menu():
    print("Graphing Calculator")
    print("0) Quit")
    print("1) Enter an equation")
    print("2) Plot points")
    print("Please select an option")
    response = input()
    return response

"""def coordinates(equation):
    f = lambda x: equation
"""

if __name__ == "__main__":
    main()

所以...我继续查看了您的整个代码。我将向您介绍我在评论中所做的事情。

def main():
    while True:
        response = raw_input("Graphing Calculator\n0) Quit\n1) Enter an equation\n2) Plot points\nPlease select an option\n>>>")

        #I removed menu() and condensed the menu into a single string. 
        #Remember to use raw_input if you just want a string of what was input; using input() is a major security risk because it immediately evaluates what was done. 

        if response == "1":
            print("Enter an equation")
            equation = raw_input("Y=")  #Same deal with raw_input. See how you can put a prompt in there? Cool, right?
            finished_equation = translate_the_equation(equation)
            #This is to fix abnormalities between Python and math. Writing this will be left as an exercise for the reader.
            f = coordinates(finished_equation)
            for i in xrange(min_value,max_value): 
              print((i,f(i))) #Prints it in (x,y) coordinate pairs.
        elif response == "2":
            x = raw_input("X=? ")
            y = raw_input("Y=? ")
            do_something(x,y)
        elif response == "0":
            print("Goodbye")
            break
        else:
            print("please enter '0', '1', or '2'") #I ordered those because it's good UX design. 
coordinates = lambda equation: eval("lambda x:"+ equation)
#So here's what you really want. I made a lambda function that makes a lambda function. eval() takes a string and evaluates it as python code. I'm concatenating the lambda header (lambda x:) with the equation and eval'ing it into a true lambda function.

我知道我要回答你的问题两次。但这一次,我要向您展示一些非常酷的东西,而不仅仅是修复您的代码。

输入:Sympy. Sympy is a module of the Numpy package that does symbolic manipulation. You can find some documentation here

太好了,又一个模块。但是它做了什么

Sympy 将方程式和表达式保存为符号而不是变量。继续 import sympy 或 pip 安装它,如果你没有它。现在,让我们为该单变量方程坐标查找器构建一个评估单元。首先,让我们确保 python 知道 x 是一个 sympy 符号。这很重要,否则 python 会将其视为普通变量,不会将控制权移交给 sympy。 Sympy 可以轻松做到这一点,甚至支持一次制作多个符号。所以继续做 x, y, z = sympy.symbols("x y z")。现在,让我们请求函数。

def make_an_equation(raw_equation = ""):
  if raw_equation == "": #This allows for make_an_equation to be used from the console AND as an interface. Spiffy, no?
    raw_equation = raw_input("Y=")
  #filter and rewrite the equation for python compatibility. Ex. if your raw_equation uses ^ for exponentiation and XOR for exclusive or, you'd turn them into ** and ^, respectively. 
  expr = eval(filtered_equation)
  return expr

好的,你有一个可以做方程式的东西。但是......你还不能完全使用它。这完全是象征性的。您必须使用 expr.subs 来用数字代替 x。

>>> my_expression = make_an_equation("x**2") #I'm assuming that the filter thing was never written. 
>>> my_expression
x**2
>>> my_expression.subs(x,5)
25

看到这有多简单了吗?你也可以变得更加复杂。让我们用另一个符号代替数字。

>>> my_expression.subs(x,z)
z**2

Sympy 包含许多非常酷的工具,例如三角函数和微积分等。无论如何,你去吧,Sympy 的介绍!玩得开心!