打印一个 Python 数组,每个元素保留 12 位小数

Print a Python array with each element to 12 decimal places

我已经有一个 existing array in Python 充满了数值。有没有什么好的函数可以让我在打印列表的时候让列表中的每个元素都显示为小数点后12位?

提前致谢!

我的列表如下所示: [array([-1, -2]), array([ 0.93396226, -0.45283019]), array([2.86792453, 1.09433962]), array([1.86681465, 2.34572697]), ... ]

您可以像这样使用 f 字符串:

a = 14.2
b = 14.123131231231231231
print(f'a = {a:.12f}')
print(f'b = {b:.12f}') 

输出:

a = 14.200000000000
b = 14.123131231231

自从我回答后,问题已经过实质性编辑。下面是旧答案。

您只需要在以下解决方案的循环中添加一个步骤:

# .12 means "to twelve decimal places"
# f means format float
format_string = "{:.12f}"

# your existing list of arrays
arrays = [array(0.1466, 5.0), array(16.789, 5.67)]

# go through your list one by one
for an_array in arrays:
    # (or whatever mechanism you use to access each number in an array)
    for number in an_array:
        # format each number using the format string we created above
        print(format_string.format(number))

旧答案(问题“如何将列表中的数字打印到小数点后 12 位”)。

字符串格式就是答案。 Here is a good rundown.

# .12 means "to twelve decimal places"
# f means format float
format_string = "{:.12f}"

# your existing list of numbers
numbers = [0.1466, 5.0, 16.789]

# go through your list one by one
for number in numbers:
    # format each number using the format string we created above
    print(format_string.format(number))

或者,使用令人愉快的 f 字符串语法:

numbers = [0.1466, 5.0, 16.789]

for number in numbers:
    print(f"{number:.12f}")