Python Equation Maker

时间:2016-04-26 06:08:32

标签: python formula

改变这个循环的最佳方法是什么,以便new_list方程将操纵值变量,但是我可以通过直接添加到循环中作为原始输入或通过添加变量来改变方程式?

#Creating the equation
def f(a_list):
    new_list = []
    for value in a_list:
        new_list += [2 * (value**3) - 1]
    return new_list

1 个答案:

答案 0 :(得分:2)

如果您希望能够以相同的方式键入方程式来修改循环的每个成员:

# python3 version
def f(a_list):
    eqn = input("Please enter an equation, using 'x' as the variable: ")
    return [eval(eqn) for x in a_list]

(如果你使用的是python 2.x,那么使用raw_input而不是input

然后:

>>> f(range(10))
Please enter an equation, using 'x' as the variable: x + 2
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

这当然是一个巨大的安全漏洞,你假设你的用户不会输入像__import__("os").unlink("some_file_name")这样的等式...