如何修复python脚本,以便以矩阵格式接收输出?

2024-06-26 09:51:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,正在尝试格式化这个输出。你知道吗

我的代码:

r1 = 1
r2 = 2
r3 = 3
r4 = 4
r5 = 5
for a in ['Interest rate','1%','2%','3%','4%','5%']:
    print (a)

for b in ['Rule of 72 Doubling time in years',72/r1,72/r2,72/r3,72/r4,72/r5]:
    print(b)

for c in ['Actual Doubling time in years','70','36','24','18','15']:
    print(c)

但是,上述代码并未以我所需的矩阵类型格式打印:

我想要的输出:

Interest Rate  Rule of 72     Actual doubling time
1%              72             70
2%              36             36

如何更改代码或添加打印代码?你知道吗


Tags: of代码infortimeruler2r3
3条回答

你可以用itertools来解决你的问题。你知道吗

代码:

import itertools
r1 = 1
r2 = 2
r3 = 3
r4 = 4
r5 = 5
list_1 = ['Interest rate','1%','2%','3%','4%','5%']
list_2 = ['Rule of 72 Doubling time in years',72/r1,72/r2,72/r3,72/r4,72/r5]
list_3 = ['Actual Doubling time in years','70','36','24','18','15']

for a, b, c in itertools.izip(x, y, z):
    print a,b,c

输出:

Interest rate Rule of 72 Doubling time in years Actual Doubling time in years
1% 72 70
2% 36 36
3% 24 24
4% 18 18
5% 14 15

理想情况下,上面的方法可以解决您的问题,但是如果您想以更好的方式打印它,那么您可以使用下面给定的方法。你知道吗

import itertools
r1 = 1
r2 = 2
r3 = 3
r4 = 4
r5 = 5
list_1 = ['Interest rate','1%','2%','3%','4%','5%']
list_2 = ['Rule of 72 Doubling time in years',72/r1,72/r2,72/r3,72/r4,72/r5]
list_3 = ['Actual Doubling time in years','70','36','24','18','15']

for a, b, c in itertools.izip(x, y, z):
    print "%-10s  %20s  %30s" % (a,b,c)

输出:

Interest rate  Rule of 72 Doubling time in years   Actual Doubling time in years
1%                            72                              70
2%                            36                              36
3%                            24                              24
4%                            18                              18
5%                            14                              15

希望这能回答你的问题!!!你知道吗

也许这会对你有所帮助:

r1 = 1
r2 = 2
r3 = 3
r4 = 4
r5 = 5

c1 = [a for a in ['Interest rate','1%','2%','3%','4%','5%']]
c2 = [b for b in ['Rule of 72 Doubling time in years', 72 / r1, 72 / r2, 72 / r3, 72 / r4, 72 / r5] ]
c3 = [c for c in ['Actual Doubling time in years', '70', '36', '24', '18', '15'] ]

for a,b,c in zip(c1,c2,c3):
    print(a,b,c)

这将产生:

Interest rate Rule of 72 Doubling time in years Actual Doubling time in years
1% 72.0 70
2% 36.0 36
3% 24.0 24
4% 18.0 18
5% 14.4 15

我不确定这个答案,希望它能帮助你。你知道吗

尝试使用字典:

r1,r2,r3,r4,r5 = 1,2,3,4,5
import pandas as pd
my_dict = { 'Interest rate' : ['1%','2%','3%','4%','5%'],
            'Rule of 72 Doubling time in years' : [72/r1,72/r2,72/r3,72/r4,72/r5],
             'Actual Doubling time in years' : ['70','36','24','18','15']}

df = pd.DataFrame(my_dict)
df

使用pandas,您将得到所需的输出矩阵

相关问题 更多 >