3

我怎样才能以表格的形式打印这个?

listex = range(nOfYears)
counter = 1
for i in listex:
        if i ==0:

            print counter, '\t',startingBalance,'\t', amountofinterest, '\t', next_balance 
            previous_balance = next_balance
            total_interest +=amountofinterest
        else:
            counter += 1

            amountofinterest = previous_balance*interestRate
            total_balance = previous_balance+amountofinterest
            print counter, '\t', previous_balance,'\t', amountofinterest, '\t', total_balance
            previous_balance = total_balance
            total_interest += amountofinterest 
print '\n', "TOTAL BALANCE IS :", previous_balance
print "TOTAL AMOUNT OF INTEREST IS %.2f:" %(total_interest)
4

1 回答 1

2

如果您想在控制台中以表格的形式打印它,您应该尝试tabulate使用非常易于使用的模块。(https://pypi.python.org/pypi/tabulate)简单的例子:

from tabulate import tabulate
table = [["Sun",696000,1989100000],["Earth",6371,5973.6],
         ["Moon",1737,73.5],["Mars",3390,641.85]]
print tabulate(table)
#-----  ------  -------------
#Sun    696000     1.9891e+09
#Earth    6371  5973.6
#Moon     1737    73.5
#Mars     3390   641.85
#-----  ------  -------------

如果你想用\t字符分隔列,你应该检查 csv 模块和 csv writer。

于 2014-12-17T12:43:10.877 回答