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

时间:2019-02-21 15:32:28

标签: python for-loop format

我是python的新手,正在尝试格式化此输出。

我的代码:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());

但是上面的代码没有以我想要的矩阵类型格式打印:

我想要的输出:

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)

如何更改代码或添加上面打印的代码?

3 个答案:

答案 0 :(得分:0)

也许这会对您有所帮助:

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

答案 1 :(得分:0)

您可以使用const subject = new Subject(); button.addEventListener(‘click’, () => subject.next('click'); subject.subscribe(x => console.log(x)); 来解决问题。

代码:

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)

希望这能回答您的问题!

答案 2 :(得分:0)

我不确定这个答案是否有望对您有所帮助。

尝试使用字典:

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

使用熊猫,您将拥有所需的输出矩阵