【发布时间】: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