将输出存储到变量并稍后打印输出

时间:2017-09-06 19:43:59

标签: python python-2.7 python-3.x

我遇到了一段代码问题。我想将输出语句存储到变量中。我想把它放在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)

2 个答案:

答案 0 :(得分:1)

我知道这听起来很简单,但是你这样做的地方:

print(formatted)

你应该这样做:

print(outputs)

或者遍历您的列表并单独打印每个列表。

for line in outputs:
  print(line)

答案 1 :(得分:1)

绝对。

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

然后在单独的行上打印所有输出:

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

那是做什么的? str.join接受一个可迭代的集合(列表)并将字符串放在它们之间。因此'X'.join(['a','b','c'])会产生'aXbXc'