首页 > 解决方案 > 如何打印一组带有格式的向量?

问题描述

我一直在尝试以类似表格的格式打印 2 个向量。当列表 A 和列表 B 中的元素没有相同数量的浮点数时,问题就来了

import math
def f(x):
    y=1/(math.sqrt(1+x))
    return y
xmin=0.0
xmax=1.0
print "Write some n:"
n=input()
x=[]
delta=((xmax-xmin)/n)
for i in range (n):
    xx=xmin+i*delta
    x.append(xx)
y=[]
b=f(x[0])
y.append(b)
for i in range (1,n-1):
    yy=2*f(x[i])
    y.append(yy)
y.append(f(x[n-1]))
for i in range(n):
    print x[i],y[i]

打印最后一行时出现问题:我想要什么:

0.0     1.0

0.125   1.88561808316

0.25    1.788854382

我得到什么:

0.0 1.0

0.125 1.88561808316

0.25 1.788854382

如何修复这些数字,以便程序正确打印结果?谢谢 :)

标签: pythonarraysprintingformat

解决方案


使用字符串格式来做到这一点。以下会将填充设置为 6 个位置:

print(”{:6}{:6}".format(x[i ], y[I]))

推荐阅读