TypeError: can't multiply sequence by non-int of type 'str' (already used int(str))

TypeError: can't multiply sequence by non-int of type 'str' (already used int(str))

我正在编写一个使用 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
    return '%s+%si' % (c * e - d * f, c * f + d * e)

但是当我 运行 它时,我得到这个错误:

In complexNumberMultiply return '%s+%si' % (c * e - d * f, c * f + d * e)
TypeError: can't multiply sequence by non-int of type 'str'

我的问题是,为什么我的 int(d[:-1]) 没有将字符串(例如 -2)转换为整数?

您将 df 转换为 int,但是 ce 呢?您正在尝试执行 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

或使用complex,这是Python中的内置类型:

>>> 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不是一个好办法。为什么不直接使用数字呢?这样你就可以避免格式化函数输入的花里胡哨的东西。

另见: Complex numbers usage in python