Search code examples
pythonlistdictionaryreturn

In python, why only the last element of a list is returned when use for loop?


The script is shown as follows:

#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))

By simply input:

>>>name

The returned result is the last element:

>>>'Line3'

I have also tried using dict(), but it still not working. Therefore, it would be so much appreciated that if someone could offer me some advice.


Solution

  • You might want that last for loop to look something like this:

    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))
    

    This won't overwrite the value of name for each loop iteration.