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

标签 python python-2.7 python-3.x

我的一段代码遇到了问题。我想将输出语句存储到变量中。我想将它放在 for 循环之外,以便它在代码末尾而不是在循环内部输出语句。这可能吗。这是我尝试过的,但我只得到一个输出,其中应该输出多个语句。

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('\n'.join(outputs))

那有什么作用? str.join 接受一个可迭代集合(列表)并将字符串放在它们之间。因此 'X'.join(['a','b','c']) 结果为 'aXbXc'

关于python - 将输出存储到变量并稍后打印输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46083189/

相关文章:

python - 列表构造中的元组拆包(python3)

python - 如何在 str.format() 中使用宽度和精度变量?

python - 在 matplotlib 条形图中强制 bin 高度为零

Python 日期时间转换

python - 如何保存使用子进程循环 python 脚本的脚本的输出?

python - 随机抽取 2 个数字,相差最小为 5

python - webapp2 是否提供某种机制来调用 HTML 表单中的 DELETE 和 PUT 操作

Python 多文件内容

python - tkinter 标签,或 "updating variables in a loop"

python - win7上python3.2和pyodbc在SQL Server 2008 R2上建表出错