【问题标题】:can't multiply sequence by non-int of type 'float'不能将序列乘以“浮点”类型的非整数
【发布时间】:2011-04-06 10:58:56
【问题描述】:

为什么我会收到“无法将序列乘以'float'类型的非整数”的错误?来自以下代码:

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

【问题讨论】:

标签: python floating-point sequence


【解决方案1】:

您将“1 + 0.01”乘以 growthRate 列表,而不是您正在迭代的列表中的项目。我已将 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])

【讨论】:

  • SO 真是太棒了……只有 11 次浏览,一分钟内就有 5 个正确答案。
【解决方案2】:
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]

【讨论】:

    【解决方案3】:

    在这一行:

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

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

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

    【讨论】:

    • @All:感谢您的及时回复。 @Nathon:我很高兴您对变量名发表了评论。学习编程时,从一开始就掌握语法规则很重要。
    【解决方案4】:

    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'
    

    【讨论】:

      【解决方案5】:

      在这一行:

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

      我认为你的意思是:

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

      当您尝试将 float 乘以 growthRates(这是一个列表)时,您会收到该错误。

      【讨论】:

        【解决方案6】:

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

        【讨论】:

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