无法用非整数类型'float'乘以序列

57 投票
6 回答
284781 浏览
提问于 2025-04-16 03:33

为什么我会在以下代码中遇到“无法用非整数类型的浮点数乘以序列”的错误呢?

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])

6 个回答

3

你现在是把“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])
21

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'
26
for i in growthRates:  
    fund = fund * (1 + 0.01 * growthRates) + depositPerYear

应该是:

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

你正在用0.01去乘一个叫做growthRates的列表对象。用一个整数去乘一个列表是可以的(这是一种语法上的简化,让你可以通过复制列表里的元素来扩展这个列表)。

举个例子:

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

撰写回答