【问题标题】:Empty list variable stored as type 'None'存储为“无”类型的空列表变量
【发布时间】:2013-05-20 20:06:29
【问题描述】:

我正在尝试在 Python 3.3.2 中编写一个简短的函数。这是我的模块:

from math import sqrt
phi = (1 + sqrt(5))/2
phinverse = (1-sqrt(5))/2

def fib(n): # Write Fibonacci numbers up to n using the generating function
    list = []
    for i in range(0,n):
        list = list.append(int(round((phi**i - phinverse**i)/sqrt(5), 0)))
    return(list)

def flib(n): # Gives only the nth Fibonacci number
    return(int(round((phi**n - phinverse**n)/sqrt(5), 0)))

if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))

当我运行 fibo.fib(6) 时,我收到以下错误:

    list = list.append(int(round((phi**i - phinverse**i)/sqrt(5), 0)))
AttributeError: 'NoneType' object has no attribute 'append'

如何纠正这个错误?

【问题讨论】:

  • 永远不要使用list 作为变量名。它是一种内置类型

标签: python list python-3.x windows-7-x64


【解决方案1】:

返回类型

list.append

None

当你做list = list.append(int(round((phi**i - phinverse**i)/sqrt(5), 0)))

它正在分配list=None

做吧

for i in range(0,n):
    list.append(int(round((phi**i - phinverse**i)/sqrt(5), 0)))

另外,list 是一个内置类型。所以使用不同的变量名。

【讨论】:

    【解决方案2】:

    append 调用不会返回列表,它会在原地更新。

    list = list.append(int(round((phi**i - phinverse**i)/sqrt(5), 0)))
    

    应该变成

    list.append(int(round((phi**i - phinverse**i)/sqrt(5), 0)))
    

    您可能还应该将参数称为 list 以外的其他名称,因为它也用于标识列表类。

    【讨论】:

      【解决方案3】:

      您也可以使用列表推导:

      def fib(n):
          '''Write Fibonacci numbers up to n using the generating function'''
      
          return [int(round((phi**i - phinverse**i)/sqrt(5), 0))) for i in range(0, n)]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-12
        • 2013-10-05
        • 2021-08-01
        相关资源
        最近更新 更多