Sympy +;的操作数类型不受支持:';符号';和';str';用数字的因子组成字符串时

Sympy +;的操作数类型不受支持:';符号';和';str';用数字的因子组成字符串时,sympy,Sympy,我得到这个错误。 宏有什么问题吗 from sympy import * var('y') x=10 d=factorint(x) print(d) for k, v in d.items(): y=y+str(k)+'^' +str(v) print(y) # {2: 1, 5: 1} # Traceback (most recent call last): # File "C:/xxx/.PyCharmCE2018.2/config/scratches/soinsuu.py",

我得到这个错误。 宏有什么问题吗

from sympy import *
var('y')
x=10
d=factorint(x)
print(d)
for k, v in d.items():
    y=y+str(k)+'^' +str(v)
print(y)

# {2: 1, 5: 1}
# Traceback (most recent call last):
#   File "C:/xxx/.PyCharmCE2018.2/config/scratches/soinsuu.py", line 9, in <module>
#     y=y+str(k)+'^' +str(v)
# TypeError: unsupported operand type(s) for +: 'Symbol' and 'str'
#
# Process finished with exit code 1
var('y')
相当于
y=symbols('y')
,因此
y
是一个符号。然后执行
y+str(k)
,添加一个符号和一个字符串。这是一个类型错误

y
的类型应为字符串。您希望该字符串以
10=
开头,因此请使用该字符串初始化它:

from sympy import *
x = 10
y = str(x) + '=' 
d = factorint(x)
print(d)
for k, v in d.items():
    y = y + str(k)+'^' +str(v)
print(y)
也就是说,你错过了算术运算。。。它应该是
*
,而不是
+
。10肯定不等于2和5之和

此外,Python为此提供了
join
string方法。使用它而不是循环:

from sympy import *
x = 10
d = factorint(x)
y = str(x) + '=' + '*'.join([str(k)+'^' +str(v) for k, v in d.items()])
print(y)
from sympy import *
x = 10
d = factorint(x)
y = str(x) + '=' + '*'.join([str(k)+'^' +str(v) for k, v in d.items()])
print(y)
def Myfactorint(x):
    return '+'.join([str(k)+'^' +str(v) for k, v in factorint(x).items()])
from sympy import *
x=10
print(x,'=',  factorint(x))
print(x,'=',Myfactorint(x))
# 10 = {2: 1, 5: 1}
# 10 = 2^1+5^1