TypeError: 'NoneType' object has no attribute '__getitem__' variable value inside a function

TypeError: 'NoneType' object has no attribute '__getitem__' variable value inside a function

我已将变量 fiblist 声明为全局变量,但它在 gen10fib 中的值为 None。

# Enter your code here. Read input from STDIN. Print output to STDOUT
#program to check if a number is fibonacci number

global fiblist 
fiblist=[0,1] #list to store generated fibonacci numbers

global Nlist
Nlist=[] # list for T test cases

global solnList
solnList=[] #contains the solution 1 is fibo 0 not fibo

global head
head=1 #to denote the maximum element in the list

def comparator(fiblist,x,head):


    if(head<x):


        gen10fib(fiblist) #generates the next 10 numbers of fibonacci sequence and appends them to fiblist

        head=max(fiblist) #upadate head

    else:

        flag=lookup(fiblist,x)

    return flag


def gen10fib(fiblist):

    fiblen=len(fiblist)

    fiblist=fiblist.sort()


    b,a=fiblist[fiblen-1],fiblist[fiblen-2] #getting the last 2 numbers

    i2=0

    for i2 in xrange(10):

      c=a+b

      fiblist.append(c)

      a=b 
      b=c



def lookup(fiblist,x):

    if x in fiblist:

        flag=1

    else:

        flag=0

    return flag




if __name__== '__main__':



 t=input()

 print t

 for i in xrange(t):

    Nlist.append(input())

 for x in Nlist:

    print x

    flag=comparator(fiblist,x,head)

 if(flag==0):

    solnList.append("IsNotFibo")

 else:

    solnList.append("IsFibo")

错误信息是

Traceback (most recent call last):
  File "G:/Codemagic/Scrap_python/dummy02", line 82, in <module>
    flag=comparator(fiblist,x,head)
  File "G:/Codemagic/Scrap_python/dummy02", line 60, in comparator
    gen10fib(fiblist) #generates the next 10 numbers of fibonacci sequence and appends them to fiblist
  File "G:/Codemagic/Scrap_python/dummy02", line 26, in gen10fib
    b,a=fiblist[fiblen-1],fiblist[fiblen-2] #getting the last 2 numbers
TypeError: 'NoneType' object has no attribute '__getitem__'

因此 fiblist 的值无法在 gen10fib 中访问,但可以在比较器函数中访问

sort方法就地排序列表,returnsNone,所以fiblist = fiblist.sort()有就地排序列表的效果,丢掉你的参考它。如果您想就地对列表进行排序,请使用 fiblist.sort() 而不进行赋值。如果您希望原始列表不被修改并且想要一个排序的副本,请使用 fiblist = sorted(fiblist).

在 gen10fib 中,您必须再次声明该变量为全局变量:

Using global variables in a function other than the one that created them