Python:TypeError:' NoneType'对象不可迭代

时间:2016-01-05 16:45:21

标签: python

我试图使用以下函数来模拟梁上的载荷:

def simulateBeamRun(personList, beam, times):

到目前为止,我已经提出了以下代码:

def createPersonList(fileName):
    """Function will go through each line of file and
    create a person object using the data provided in
    the line and add it to a list
    """
    theFile = open(fileName)
    next(theFile)
    #array = []
    for line in theFile:
        aList = line.split(',')
        bList = map(lambda s: s.strip('\n'), aList)
        cList = [float(i) for i in bList]
        print cList

def simulateBeamRun(personList, beam, times):
    """Takes a list of times covering the duration of
    the simulation (0-35 s), the list of person
    objects and a beam object to simulate a beam run
    """
    dList = []
    for time in times:
        eList = []
        for person in personList:
            loadTuples = personModel.person.loadDisplacement(time)
            if beamModel.beam.L > loadTuples[1] > 0:
                 eList.append(loadTuples)
            else:
                return None
        beamModel.beam.setLoads(eList)
        dList.append(beamModel.beam.getMaxDeflection())

但是,我在尝试运行该函数时遇到以下错误(在我给它任何输入之前:

for person in personList:
TypeError: 'NoneType' object is not iterable

2 个答案:

答案 0 :(得分:4)

为了进行迭代,personList需要包含一些值。

如果您使用[{1}}功能创建personList,则需要return a value。否则,该列表不存在于createPersonList之外。

createPersonList

然后,def createPersonList(fileName): # do stuff to create cList return cList personList = createPersonList(myFile) 将具有值,您可以在后续函数中使用它。

personList

如果您想在simulateBeamRun(personList, beam, times) 没有值的情况下完全避免运行该循环,请包含条件。

personList

答案 1 :(得分:1)

可以使用以下代码

def createPersonList(fileName):
    """Function will go through each line of file and
    create a person object using the data provided in
    the line and add it to a list"""
    cList=[]#see my comments. if the following loop not happen, still return []

    theFile = open(fileName)
    next(theFile)
    #array = []
    for line in theFile:
        aList = line.split(',')
        bList = map(lambda s: s.strip('\n'), aList)
        cList += [float(i) for i in bList]# if bList is iterable, [float(i) for i in bList] should be a list (including [])
    return cList#according to your comments, should return here.

float(i)可能会抛出错误,因此请使用try-except。 我认为应该在这个函数中完成与personList相关的检查,应该记录错误信息。