簡體   English   中英

將輸出存儲到變量並稍后打印輸出

[英]Storing Output to Variable and Printing Output Later

我在一段代碼上遇到麻煩。 我想將輸出語句存儲到變量。 我想將其放在for loop之外for loop以便它在我的代碼末尾而不是循環內輸出語句。 這可能嗎。 這是我嘗試過的方法,但是我只有一個輸出,其中應該輸出多個語句。

outputs=[]
if Year in mydict and data_location in mydict[Year]:  
    busses_in_year = mydict[Year]
    #print("Here are all the busses at that location for that year and the new LOAD TOTAL: ")
    #print("\n")

    #Busnum, busname,scaled_power read from excel sheet matching year and location

    for busnum,busname,scaled_power in busses_in_year[data_location]:
        scaled_power= float(scaled_power)
        busnum = int(busnum)
        output='Bus #: {}\t Area Station: {}\t New Load Total: {} MW\t'
        formatted = output.format(busnum, busname, scaled_power)
        outputs.append(formatted)

        psspy.bsys(1,0,[0.0,0.0],0,[],1,[busnum],0,[],0,[])
        psspy.scal_2(1,0,1,[0,0,0,0,0],[0.0,0.0,0.0,0.0,0.0,0.0,0.0])
        psspy.scal_2(0,1,2,[0,1,0,1,0],[scaled_power,0.0,0,-.0,0.0,-.0,0])
        psspy.fdns([0,0,1,1,0,0,0,0])


else:
    exit

print(formatted)

我知道這聽起來很簡單,但是您在執行此操作的地方:

print(formatted)

您應該這樣做:

print(outputs)

或者遍歷您的列表並單獨打印每個列表。

for line in outputs:
  print(line)

絕對。

首先,您要打印formatted ,而不是outputs

然后在單獨的行上打印所有輸出:

print('\\n'.join(outputs))

那是做什么的? str.join接受一個可迭代的集合(一個列表),並將字符串放在它們之間。 所以'X'.join(['a','b','c'])結果為'aXbXc'

暫無
暫無

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

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