在python中,为什么在使用for循环时只返回列表的最后一个元素?

在python中,为什么在使用for循环时只返回列表的最后一个元素?,python,list,dictionary,return,Python,List,Dictionary,Return,脚本如下所示: #add powerfactory.pyd path to python path import sys sys.path.append("C:\\Program Files\\DIgSILENT\\PowerFactory 2017 SP2\\Python\\3.6") if __name__ == "__main__": #import powerfactory module import powerfactory #start powerfactory mo

脚本如下所示:

#add powerfactory.pyd path to python path
import sys
sys.path.append("C:\\Program Files\\DIgSILENT\\PowerFactory 2017 
SP2\\Python\\3.6")

if __name__ == "__main__":
#import powerfactory module

    import powerfactory

#start powerfactory module in unattended mode (engine mode)
app=powerfactory.GetApplication()



#active project
project=app.ActivateProject('Python Test') #active project "Python Test"
# prj=app.GetActiveProject   #returns the actived project

#run python code below
ldf=app.GetFromStudyCase('ComLdf') #calling loadflow command 
ldf.Execute() #executing the load flow command

#get the list of lines contained in the project
lines=app.GetCalcRelevantObjects('*.ElmLne') #returns all relevant objects

for line in lines: #get each element out of list
    name=line.loc_name #get name of the line
    value=line.GetAttribute('c:loading') 
    print('Loading of the line: %s = %.2f%%'%(name,value))
只需输入:

>>>name
返回的结果是最后一个元素:

>>>'Line3'

我也尝试过使用dict(),但仍然不起作用。因此,如果有人能给我一些建议,我将不胜感激。

您可能希望最后一个for循环看起来像这样:

name = []
for line in lines: #get each element out of list
    name.append(line.loc_name) #get name of the line
    value=line.GetAttribute('c:loading') 
    print('Loading of the line: %s = %.2f%%'%(name,value))

这不会覆盖每个循环迭代的name值。

您的print语句在for loopHa之外。我明白了,真尴尬。非常感谢。但是,当我简单地键入name时,返回的结果仍然是最后一个元素。
列表有多少个元素?
名称
被重新分配给每一行,因此保留最后一行的值。