簡體   English   中英

在python中,為什么在使用for循環時僅返回列表的最后一個元素?

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

該腳本如下所示:

#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值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM