Python:TypeError:“NoneType”对象不是iterab

2024-09-27 09:29: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

Tags: andoftheinforobjectdefline
2条回答

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

如果使用函数createPersonList创建personList,则需要return a value。否则,该列表不存在于createPersonList之外。

def createPersonList(fileName):
    # do stuff to create cList
    return cList

personList = createPersonList(myFile)

然后,personList将有值,您可以在后续函数中使用它。

simulateBeamRun(personList, beam, times)

如果要避免在personList没有值的情况下运行该循环,请包含条件。

if personList is None:
    print "No values in personList"
else:
    for person in personList:
        # do stuff with person

下面的代码可以帮助您吗

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相关的检查,应该记录错误信息。

相关问题 更多 >

    热门问题