TypeError:“ headers”是print()的无效关键字参数

时间:2019-09-06 14:08:55

标签: python-3.x tabulate

我最近将制表符安装到了conda上,并尝试使用打印语法将结果制表 来源:Printing Lists as Tabular Data 但我收到“ TypeError:'headers'是print()的无效关键字参数”

我尝试过“ print(tabulate([['Alice',24],['Bob',19]],headers = ['Name','Age'],tablefmt ='orgtbl'))“ < / p>

from tabulate import tabulate
i: int
with open("incre.txt", "w") as file:

    for i in range(1, 100,5):
        mol = int((i*50)/(i+50))
        file.write(str(i)+ " " +str(mol) + "\n")
    print(tabulate([[i], [mol]]), headers=['i' , 'mol'], tablefmt='orgtbl')
    file.close()

预期结果将根据

Expected output example

我遇到类型错误,我在这里想念什么?

1 个答案:

答案 0 :(得分:3)

您写括号的方式有误,请尝试以下行:

print(tabulate([[i], [mol]], headers=['i' , 'mol'], tablefmt='orgtbl'))

您正在做的事情就是这样:

x = tabulate([[i], [mol]]
print(x, headers=['i' , 'mol'], tablefmt='orgtbl')

如您所见,您正在尝试使用printheaders关键字调用tablefmt方法,这会导致错误:'headers' is an invalid keyword argument for print()

更新:

我不确定,但是我认为您想要实现的目标是:

from tabulate import tabulate

values = []

for i in range(1, 100,5):
    mol = int((i*50)/(i+50))
    values.append([i, mol])

print(tabulate(values, headers=['i' , 'mol'], tablefmt='orgtbl'))

在您的代码中,您从while循环中退出后正在打印imol,那么您将只打印它们的最后一个值...