Python 类型错误:can';t将序列乘以类型为'的非整数;str';(已使用int(str))
我正在编写一个使用python2.7计算复数乘法的函数。功能是:Python 类型错误:can';t将序列乘以类型为'的非整数;str';(已使用int(str)),python,string,complex-numbers,Python,String,Complex Numbers,我正在编写一个使用python2.7计算复数乘法的函数。功能是: def complexNumberMultiply(self, a, b): """ :type a: str :type b: str :rtype: str """ c,d = a.split('+') e,f = b.split('+') d = int(d[:-1]) f = int(f[:-1]) print c,d,e,f ret
def complexNumberMultiply(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
c,d = a.split('+')
e,f = b.split('+')
d = int(d[:-1])
f = int(f[:-1])
print c,d,e,f
return '%s+%si' % (c * e - d * f, c * f + d * e)
但当我运行它时,我会得到以下错误:
以复数形式
返回“%s+%si%”(c*e-d*f,c*f+d*e)TypeError:无法将序列与'str'类型的非int相乘
我的问题是,为什么我的int(d[:-1])没有将字符串(例如-2)转换为整数?您将
d
和f
转换为int
,但是c
和e
呢?您正在尝试执行c*e
,不能将字符串乘以字符串
考虑:
def complexNumberMultiply(a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
split_a = a.split('+')
split_b = b.split('+')
c, d = int(split_a[0]), int(split_a[-1][0])
e, f = int(split_b[0]), int(split_b[-1][0])
print (c,d,e,f)
return '%s + %si' % (c * e - d * f, c * f + d * e)
print(complexNumberMultiply('1+2i', '3+4i'))
# 1 2 3 4
# -5+10i
或者使用Python中的内置类型complex
:
>>> complex('1+2j') * complex('3+4j')
(-5+10j)
>>> (1+2j) * (3+4j)
(-5+10j)
您将
d
和f
转换为int
,但是c
和e
呢?您正在尝试执行c*e
,不能将字符串乘以字符串
考虑:
def complexNumberMultiply(a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
split_a = a.split('+')
split_b = b.split('+')
c, d = int(split_a[0]), int(split_a[-1][0])
e, f = int(split_b[0]), int(split_b[-1][0])
print (c,d,e,f)
return '%s + %si' % (c * e - d * f, c * f + d * e)
print(complexNumberMultiply('1+2i', '3+4i'))
# 1 2 3 4
# -5+10i
或者使用Python中的内置类型complex
:
>>> complex('1+2j') * complex('3+4j')
(-5+10j)
>>> (1+2j) * (3+4j)
(-5+10j)
虚数在Python中被识别为对象,就像整数、浮点数……:
>>> complexN = 33 + 2j
>>> complexN
(33+2j)
>>> complexN.real # real part
33.0
>>> complexN.imag # imaginary part
2.0
添加复数:
>>> complex + (33+2j)
(66+4j)
2j
是虚部,实部是33。这是Python中处理复数的推荐方法
但是如果你坚持使用你的函数进行实验,我不认为使用str
然后转换成int
是一个好方法。为什么不直接使用数字呢?通过这种方式,您将避免对函数的输入进行格式化的麻烦
另见:
在Python中,虚数被识别为对象,就像整数、浮点数……:
>>> complexN = 33 + 2j
>>> complexN
(33+2j)
>>> complexN.real # real part
33.0
>>> complexN.imag # imaginary part
2.0
添加复数:
>>> complex + (33+2j)
(66+4j)
2j
是虚部,实部是33。这是Python中处理复数的推荐方法
但是如果你坚持使用你的函数进行实验,我不认为使用str
然后转换成int
是一个好方法。为什么不直接使用数字呢?通过这种方式,您将避免对函数的输入进行格式化的麻烦
另见:
1)提供用于测试此函数的输入2)您不转换
c
和e
3)您是否知道python中存在复数类型?1)提供用于测试此函数的输入2)您不转换c
和e
3)您是否知道python中存在复数类型蟒蛇?谢谢。为什么我甚至没有注意到c,e>(1+2j)*(3+4j)
也可以工作-无需调用复杂的构造函数()
构造函数。@TimPietzcker:当然,但输入就是它的样子…谢谢。为什么我甚至没有注意到c,e>(1+2j)*(3+4j)
也可以工作-不需要调用复杂的构造函数()
构造函数。@TimPietzcker:当然,但输入就是它的本来面目…