【问题标题】:In python, why only the last element of a list is returned when use for loop?在python中,为什么使用for循环时只返回列表的最后一个元素?
【发布时间】:2017-10-22 11:06:15
【问题描述】:

脚本如下所示:

#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 循环之外
  • 哈。我明白了,好尴尬。非常感谢。
  • 但是同样,当我简单地输入名称时,返回的结果仍然是最后一个元素。
  • lines 列表有多少个元素?
  • name 为每一行重新分配,因此保留最后一行的值。

标签: python list dictionary return


【解决方案1】:

您可能希望最后一个 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 值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 2021-08-31
    • 2021-09-20
    • 2019-11-13
    相关资源
    最近更新 更多