本文介绍了同情未知的任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个用于求解方程的 Python 程序:

from sympy 导入符号,Eq,求解list1 = ['x', 'y'] #<--- 用户输入的字母list1[0] = symbols(list1[0]) #<--- 未知 x 的赋值list1[1] = symbols(list1[1]) #<--- 未知 y 的赋值eq1 = Eq(x*2 - 5*x + 6 + y, 0) #

我想为list1"的第一个和第二个对象赋值,在本例中为x = symbols('x')'和'y = symbols('y')'.所以我尝试用 list1[0] 替换x",用 list1[1] 替换y",因为它可以是基于用户输入的任何字母.但是脚本在第六行仍然说x 未定义".那么,有没有办法给数组的某一项赋值?

解决方案

当您开始使用 SymPy 时,需要一段时间才能弄清楚 SymPy 对象和 Python 变量之间的区别.尽量记住,每个变量都是一个 Python 变量,你分配给它什么取决于你.

在第 6 行中,您要使用变量 xy.您可以查看前面几行,看到您从未定义过 x(它必须在 = 的 lhs 上).这将纠正这种情况:

>>>x, y = 地图(符号,列表 1)

就字符串而言,list1 中的内容无关紧要.它们甚至可以是 ['a', 'b'].无论它们是什么,它们都将用于创建 SymPy 符号,并将它们分配给 Python 变量 xy.然后它们将出现在您正在求解的方程的结果中:

>>>list1 = list('ab')>>>x, y = 地图(符号,列表 1)>>>解决(Eq(x*2 - 5*x + 6 + y, 0), dict=True)[{a: b/3 + 2}]

I'm trying to create a python program for solving equations:

from sympy import symbols, Eq, solve

list1 = ['x', 'y']                 #<--- Letters of the user input
list1[0] = symbols(list1[0])       #<--- Assignment of the unknown x
list1[1] = symbols(list1[1])       #<--- Assignment of the unknown y
eq1 = Eq(x*2 - 5*x + 6 + y, 0)     #<--- Equation
res = solve(eq1, dict=True)        #<--- Solving
print(res)

I want assign a value to the first and the second object of the 'list1', in this case 'x = symbols('x')' and 'y = symbols('y')'. So I tried replacing the 'x' with list1[0] and the 'y' with list1[1] because it can be any letter based on user input. But the script still saying 'x is not defined' at the sixth line. So, is there a way to assign a value to an item of an array?

解决方案

When you are getting started with SymPy it takes a while to keep straight the difference between SymPy objects and Python variables. Try to keep in mind that every variable is a Python variable and what you assign to it is up to you.

In line 6 you want to use variables x and y. You can look in the preceding lines to see that you never defined an x (which would have to be on the lhs of an =). This will remedy the situation:

>>> x, y = map(Symbol, list1)

It doesn't matter what is in list1 in terms of strings. They could even be ['a', 'b']. Whatever they are they will be used to create SymPy symbols and they will be assigned to the Python variables x and y. They will then appear in the results of the equation that you are solving:

>>> list1 = list('ab')
>>> x, y = map(Symbol, list1)
>>> solve(Eq(x*2 - 5*x + 6 + y, 0), dict=True)
[{a: b/3 + 2}]

这篇关于同情未知的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 12:09