【问题标题】:TypeError: 'float' object does not support item assignmentTypeError:“浮动”对象不支持项目分配
【发布时间】:2019-03-21 04:00:27
【问题描述】:

我理解错误背后的信息,但在理解如何克服它时我迷失了。我想要做的是,在 for/loop 中,名为pancake 的变量将前一次迭代pancake[i - 1] 的值用作函数exit 调用的第一个参数。

我遇到的错误:

TypeError: 'float' object does not support item assignment

我的代码:

   def exit(number):
        def son():
            geometric = (math.exp(2))
            pancake = number * geometric
            return pancake

        return son()

    pancake_ac = exit()()
    pancake_ac[0] = pancake_ac

    for i in range(1, 10):
        pancake_ac[i] = exit(pancake_ac[i - 1])

【问题讨论】:

    标签: python loops variables


    【解决方案1】:

    precio_accion 不是listdict,它是一个浮点数,所以你根本不需要precio_accion[0] = precio_accion 行。如果你想要list

    import math
    import random
    
    
    def funcion_gbm(pi = 100, media = 0.10, volatilidad = 0.05):
        m = media
        v = volatilidad
    
        def funcion_anidada():
            exponencial = math.exp((m - (1/2) * v**2) * (1/365) +
                                   v * math.sqrt(1/365) * random.normalvariate(0, 1))
            precio = pi * exponencial
            return precio
    
        return funcion_anidada
    
    
    precio_accion = funcion_gbm()()
    
    # Now precio_accion is a list and your iteration will work
    precio_accion = [precio_accion]
    

    编辑

    现在让我们进入你的循环。首先,你的target_price 没有改变,那为什么还要重新定义呢?您可以在循环之外定义一次:

    target_price = 125
    
    for rueda in range(1,1000):
        # Now you need to append to the list rather than trying to
        # access other elements that aren't in the list yet
        precio_accion.append(funcion_gbm(precio_accion[rueda - 1]))
    
        # You're comparing the last item in the list every time, so
        # you can just access it with -1
        if precio_accion[-1] == target_price:
            print("reached")
    
        # No need for else since it's just continuing the loop
    
    

    【讨论】:

      猜你喜欢
      • 2018-03-13
      • 2016-07-31
      • 2014-02-18
      • 2017-03-26
      • 2021-08-05
      • 1970-01-01
      • 1970-01-01
      • 2022-08-08
      相关资源
      最近更新 更多