在 Python 3 中制作表格(初学者)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43889141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Making a table in Python 3(beginner)
提问by Fruitdruif
So I just started learning Python 3 in school, and we had to make a function that takes aas a parameter, chooses a reasonable value of x, and returns an estimate of the square root of a.
所以我刚开始在学校学习 Python 3,我们必须制作一个函数,将a作为参数,选择一个合理的 x 值,并返回a平方根的估计值。
We also had to make a function to test it. We had to write a function named test_square_root that prints a table, where The first column is a number, a; the second column is the square root of acomputed with the first function; the third column is the square root computed by math.sqrt; the fourth column is the absolute value of the difference between the two estimates.
我们还必须制作一个函数来测试它。我们必须编写一个名为 test_square_root 的函数来打印一个表,其中第一列是一个数字a;第二列是用第一个函数计算的a 的平方根;第三列是 math.sqrt 计算的平方根;第四列是两个估计值之间差异的绝对值。
I wrote the first function to find the square root, but I don't know how to make a table like that. I've read other questions on here about tables in Python3 but I still don't know how to apply them to my function.
我写了第一个求平方根的函数,但我不知道如何制作这样的表格。我在这里阅读了有关 Python3 中表格的其他问题,但我仍然不知道如何将它们应用到我的函数中。
def mysqrt(a):
for x in range(1,int(1./2*a)):
while True:
y = (x + a/x) / 2
if y == x:
break
x = y
print(x)
print(mysqrt(16))
回答by Hyman Evans
If you're allowed to use libraries
如果您被允许使用库
from tabulate import tabulate
from math import sqrt
def mysqrt(a):
for x in range(1, int(1 / 2 * a)):
while True:
y = (x + a / x) / 2
ifjl y == x:
break
x = y
return x
results = [(x, mysqrt(x), sqrt(x)) for x in range(10, 20)]
print(tabulate(results, headers=["num", "mysqrt", "sqrt"]))
Outputs
输出
num mysqrt sqrt
----- -------- -------
10 3.16228 3.16228
11 3.31662 3.31662
12 3.4641 3.4641
13 3.60555 3.60555
14 3.74166 3.74166
15 3.87298 3.87298
16 4 4
17 4.12311 4.12311
18 4.24264 4.24264
19 4.3589 4.3589
Failing that there's plenty of examples on how to print tabular data (with and without libraries) here: Printing Lists as Tabular Data
如果没有关于如何在此处打印表格数据(带和不带库)的大量示例:将列表打印为表格数据