不能将序列乘以'float'类型的非int

时间:2010-08-31 19:15:49

标签: python floating-point sequence

级别:初学者

为什么我会得到错误“不能将序列乘以'int'类型的非int”?

def nestEgVariable(salary, save, growthRates):
    SavingsRecord = []
    fund = 0
    depositPerYear = salary * save * 0.01
    for i in growthRates:  
        fund = fund * (1 + 0.01 * growthRates) + depositPerYear
        SavingsRecord += [fund,]
    return SavingsRecord 


print nestEgVariable(10000,10,[3,4,5,0,3])

感谢 巴巴

7 个答案:

答案 0 :(得分:19)

for i in growthRates:  
    fund = fund * (1 + 0.01 * growthRates) + depositPerYear

应该是:

for i in growthRates:  
    fund = fund * (1 + 0.01 * i) + depositPerYear

您将使用growRates列表对象乘以0.01。将列表乘以整数是有效的(它是重载的语法糖,允许您使用其元素引用的副本创建扩展列表)。

示例:

>>> 2 * [1,2]
[1, 2, 1, 2]

答案 1 :(得分:13)

Python允许您将序列相乘以重复其值。这是一个直观的例子:

>>> [1] * 5
[1, 1, 1, 1, 1]

但它不允许你用浮点数来做:

>>> [1] * 5.1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'

答案 2 :(得分:3)

您将growRate列表的“1 + 0.01”乘以,而不是您正在迭代的列表中的项目。我已将i重命名为rate并改为使用它。请参阅下面的更新代码:

def nestEgVariable(salary, save, growthRates):
    SavingsRecord = []
    fund = 0
    depositPerYear = salary * save * 0.01
    #    V-- rate is a clearer name than i here, since you're iterating through the rates contained in the growthRates list
    for rate in growthRates:  
        #                           V-- Use the `rate` item in the growthRate list you're iterating through rather than multiplying by the `growthRate` list itself.
        fund = fund * (1 + 0.01 * rate) + depositPerYear
        SavingsRecord += [fund,]
    return SavingsRecord 


print nestEgVariable(10000,10,[3,4,5,0,3])

答案 3 :(得分:2)

在这一行:

fund = fund * (1 + 0.01 * growthRates) + depositPerYear

growthRates是一个序列([3,4,5,0,3])。您不能将该序列乘以float(0.1)。看起来你想放在那里的是i

顺便说一下,i不是该变量的好名字。考虑一些更具描述性的内容,例如growthRaterate

答案 4 :(得分:1)

在这一行:

fund = fund * (1 + 0.01 * growthRates) + depositPerYear

我认为你的意思是:

fund = fund * (1 + 0.01 * i) + depositPerYear

当你尝试将一个浮点数乘以growRates(这是一个列表)时,就会出现错误。

答案 5 :(得分:0)

因为growRates是一个序列(你甚至在迭代它!)并且你将它乘以(1 + 0.01),这显然是一个浮点数(1.01)。我猜你的意思是for growthRate in growthRates: ... * growthrate

答案 6 :(得分:0)

读取带有%的列时出现此错误。例如,我有一列具有百分比的列,例如60%等,当读取具有上述值的.csv文件时,我得到了确切的错误“无法将序列乘以'float'类型的非整数”。 / p>

我从该列中删除了%符号,并重新处理了相同的代码(例如该列现在只有60),现在错误消失了,而无需更改代码。