TypeError:'NoneType'对象没有属性'__getitem__'

时间:2013-12-04 11:43:46

标签: python

嗨所以我创建了这个名为runloopg(x,y,z)的函数,它生成一个列表,但我无法调用列表中的项目:

p=runloopg(10,0.1,6)
<generator object rtpairs at 0x000000000BAF1F78>
[(0,0,0,0,0,1), (0.01,0,0,0,0,1), (0.0062349,0.00781831,0,0,0,1), (-0.00222521,0.00974928,0,0,0,1), (-0.00900969,0.00433884,0,0,0,1), (0.0549583,-0.0712712,0,0,0,1), (0.0627244,-0.0645419,0,0,0,1), (0.0696727,-0.0569711,0,0,0,1), (0.0757128,-0.0486577,0,0,0,1), (0.0807659,-0.0397099,0,0,0,1), (0.084766,-0.0302444,0,0,0,1), (0.0876611,-0.0203847,0,0,0,1), (0.0894134,-0.0102592,0,0,0,1)]

但是,当我在列表中调用项目时:

p[0]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-240-a69904524460> in <module>()
----> 1 p[0]

TypeError: 'NoneType' object has no attribute '__getitem__'

这是runloopg的代码:

import numpy
import raytracer29

def rtpairs(R, N):
    for i in range(len(R)):
        r=R[i]
        n=N[i]
        for j in range(n):
            t = j*2*numpy.pi/n
            yield r,t

def rtuniform(n, rmax, m):
    R=numpy.arange(0,rmax,rmax/n)
    N=numpy.arange(1, n*m, m)
    return rtpairs(R, N)

def runloopg(n, rmax, m):
    #print  rtuniform(n, rmax, m)
    bund = []
    for r,t in rtuniform(n, rmax, m):
        myRay = raytracer29.Ray(r * numpy.cos(t), r * numpy.sin(t),0,0,0,1)        
        bund.append(myRay)
    return bund

4 个答案:

答案 0 :(得分:1)

您没有发布相关代码 - 您的函数的定义 - 但很明显,此函数返回None

编辑:从您发布的代码段runloopg确实确实返回了一个列表,因此问题出在其他地方。我看到你的代码片段以注释掉的print语句开头,打印调用rtuniform的返回值,这与你发布的交互式会话相匹配。我的猜测是你正在执行一个旧版本的函数,它刚刚打印并立即退出(隐含地返回None),然后你编辑了你的代码但是没能正确地重新加载你的函数。

答案 1 :(得分:0)

由于您的方法返回了一个生成器,您需要使用它:

for i in runloopg(10,0.1,6):
   print(i)

p = list(runloopg(10,0.1,6))

# If you just want the first item:

first_item = next(runloopg(10,0.1,6))

答案 2 :(得分:0)

您的runloopg函数似乎缺少return。所以,它做了这样的事情:

def runloopg():
   [(0,0,0,0,0,1), (0.01,0,0,0,0,1), (0.0062349,0.00781831,0,0,0,1)] # and the rest

或者这个:

def runloop():
    x = [(0,0,0,0,0,1), (0.01,0,0,0,0,1), (0.0062349,0.00781831,0,0,0,1)] # and the rest

而不是:

def runloopg():
    return [(0,0,0,0,0,1), (0.01,0,0,0,0,1), (0.0062349,0.00781831,0,0,0,1)] # and the rest

在第一个版本中,运行该行,然后立即丢弃其结果,并继续执行该功能。在第二个中,结果存储在变量中,并且函数继续。在这两种情况下,函数都会结束 - 当发生这种情况时,Python将为您返回None。在上一个版本中,系统会返回您计算的结果,并最终分配给p - 因此p将成为一个列表,p[0]将起作用。

答案 3 :(得分:-2)

返回生成器对象。一旦你使用了发电机,它就会耗尽,你就不能再使用它了。

但你可以将所有值作为列表:

p = list(runloopg(10,0.1,6))