2017-09-06 11 views
1

私のコードに問題があります。私は出力文を変数に格納したい。私はfor loopの外に置いて、ループ内ではなくコードの最後に文を出力します。これは可能ですか?これは私が試みたものですが、複数のステートメントを出力する必要がある場合は1つの出力しか得られません。変数を出力して出力を後で保存する

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

なぜ 'outputs'ではなく' formatted'を出力していますか? 'outputs'はすべてのフォーマットされた出力文字列のリストです。 – birryree

答えて

1

です。

まず、あなたがformattedを、印刷していない、あなたのoutputs

その後別々の行に出力のすべてを印刷する:

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

はそれが何をしますか? str.joinは反復可能なコレクション(リスト)をとり、それらの間に文字列を置きます。だから'X'.join(['a','b','c'])の結果は'aXbXc'

1

私は、これは単純な音を知っているが、あなたはこれをやっている場所:

print(formatted) 

あなたがこれを行うべきである:

print(outputs) 

またはあなたのリストを反復処理し、それぞれを個別に印刷します。

for line in outputs: 
    print(line) 
+0

Python 3では 'print()'の括弧が必要であることを強調したいだけです – chowsai

+0

ありがとう。 '' 'Bus#:126688 \ t Area Station:Buchanan \ t新しい積算合計:125.0 MW \ t'」というように、それぞれのステートメントを新しい行に印刷する方法はありますか? 'Bus#:126695 \ tエリアステーション:Millwood West \ t新しい負荷合計:85.0 MW \ t'、 'Bus#:126696 \ tエリアステーション:Ossining West \ t新しい負荷合計:77.0 MW \ t'] ' – Danny

+0

各エントリの先頭または末尾に改行( '\ n')を追加することもできます。 @chowsai、ありがとう。私は2.7に慣れています:P – Ski

関連する問題