【问题标题】:TypeError: can't multiply sequence by non-int of type 'float' when multiplying an integer with a list of integersTypeError:当将整数与整数列表相乘时,不能将序列乘以“浮点”类型的非整数
【发布时间】:2021-03-06 15:39:03
【问题描述】:

我的代码:

import numpy as np
import sympy as sym

df = [0.99833714, 0.96852   , 0.95101663, 0.92618755]
mat = list(np.arange(1,5)/2)

def task2(df,mat,comp):
    """
    inputs:
    df - list with discount factors
    mat - list with respective maturities
    comp - either a positive integer for compounding frequency per year or 0 for continuous compounding
    returns: numpy array with spot rates (in decimals p.a.) in the same order as inputs
    """
    
    if comp > 0:
        rate = comp*([x for x in df]**(-1/comp*[y for y in mat])-1)
    else:
        rate = -(1/[y for y in mat])*np.log([x for x in df])
    
    rate.asarray()
    
    return rate

这是我在玩 task2() 时遇到的错误,我不明白为什么会产生错误,而且我在 StackOverflow 或其他地方找不到任何相关内容:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-102-430bc9fc5d7f> in <module>
----> 1 print(task2(df,mat,2))
      2 print(task2(df,mat,0))

<ipython-input-100-5b721054deb4> in task2(df, mat, comp)
     16 
     17     if comp > 0:
---> 18         rate = comp*([x for x in df]**(-1/comp*[y for y in mat])-1)
     19     else:
     20         rate = -(1/[y for y in mat])*np.log([x for x in df])

TypeError: can't multiply sequence by non-int of type 'float'

如果 `comp 肯定是整数,谁能告诉我为什么会出现这个错误?

【问题讨论】:

  • 为什么是[x for x in df] 而不仅仅是df?在您的代码上下文中,您正在使用列表推导将列表转换为现有的列表。

标签: python typeerror calculation


【解决方案1】:

在下面的代码部分中,-1/comp 将导致浮点数,除非 comp 为 1 或者您使用的是 Python 2。

(-1/comp*[y for y in mat])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-19
    • 2013-09-11
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    • 2012-09-17
    相关资源
    最近更新 更多