【问题标题】:TypeError: can't multiply sequence by non-int of type 'str' (already used int(str))TypeError:不能将序列乘以“str”类型的非整数(已使用 int(str))
【发布时间】:2017-12-01 14:05:56
【问题描述】:

我正在编写一个使用 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)

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

在复数乘法中 返回 '​​%s+%si' % (c * e - d * f, c * f + d * e)
TypeError:不能将序列乘以“str”类型的非整数

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

【问题讨论】:

  • 1) 提供你用来测试这个函数的输入 2) 你不转换ce 3) 你知道python中有一个复数类型吗?跨度>

标签: python string complex-numbers


【解决方案1】:

虚数在 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

【讨论】:

    【解决方案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)
    

    【讨论】:

    • 谢谢。我怎么都没注意到 c,e >
    • (1+2j)*(3+4j) 也可以工作 - 无需调用 complex() 构造函数。
    • @TimPietzcker:当然,但是输入就是这样……
    猜你喜欢
    • 2010-11-15
    • 1970-01-01
    • 2019-04-12
    • 2021-08-07
    • 2013-07-03
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多