Python 中漂亮地打印浮点数列表

Python 中漂亮地打印一个浮点数列表:

  1. 使用列表推导来遍历列表。
  2. 使用格式化字符串文字将每个浮点数格式化为指定的小数位数。
  3. 使用 print() 函数打印结果。
list_of_floats = [3.596821, 2.423287, 5.9283237, 7.23894823]

# ✅ pretty print list of floats formatted to 2 decimals
result = [f'{item:.2f}' for item in list_of_floats]
print(result)  # 👉️ ['3.60', '2.42', '5.93', '7.24']

# ---------------------------------------------------------

# ✅ pretty print list of floats formatted to 3 decimals
result = [f'{item:.3f}' for item in list_of_floats]
print(result)  # 👉️ ['3.597', '2.423', '5.928', '7.239']

# ---------------------------------------------------------

# ✅ pretty print list of floats without a comma between elements

result = [f'{item:.2f}' for item in list_of_floats]
print(str(result).replace(',', ''))  # 👉️ ['3.60' '2.42' '5.93' '7.24']

print(' '.join(result))  # 👉️ 3.60 2.42 5.93 7.24

第一步是使用列表推导来迭代浮点数列表。

list_of_floats = [3.596821, 2.423287, 5.9283237, 7.23894823]

result = [f'{item:.2f}' for item in list_of_floats]
print(result)  # 👉️ ['3.60', '2.42', '5.93', '7.24']

在每次迭代中,我们使用格式化字符串文字将浮点数格式化为 2 位小数并返回结果。

格式化字符串文字 (f-strings) 让我们通过在字符串前加上 f 来在字符串中包含表达式。

确保将表达式用大括号括起来 – {expression}

格式化字符串文字还使我们能够在表达式块中使用格式特定的迷你语言。

num = 3.596821

print(f'{num:.3f}')  # 👉️ '3.597'
print(f'{num:.4f}')  # 👉️ '3.5968'

句点后的数字是浮点数应具有的小数位数。

如果我们将小数位数存储在变量中,请将其用大括号括在 f 字符串中。

list_of_floats = [3.596821, 2.423287, 5.9283237, 7.23894823]

decimal_places = 2

result = [f'{item:.{decimal_places}f}' for item in list_of_floats]
print(result)  # 👉️ ['3.60', '2.42', '5.93', '7.24']

如果我们需要将浮点数列表格式化为小数点后的特定位数并在不使用逗号分隔符的情况下打印它们,请使用 str.replace() 方法。

list_of_floats = [3.596821, 2.423287, 5.9283237, 7.23894823]

result = [f'{item:.2f}' for item in list_of_floats]
print(str(result).replace(',', ''))  # 👉️ ['3.60' '2.42' '5.93' '7.24']

我们将列表转换为字符串并使用 str.replace() 方法删除逗号。

str.replace 方法返回字符串的副本,其中所有出现的子字符串都被提供的替换项替换。

该方法采用以下参数:

  • old 字符串中我们要替换的子串
  • new 替换每次出现的 old
  • count 仅替换第一个 count 出现(可选)

如果需要打印不带方括号和逗号的浮点列表,可以使用 str.join() 方法。

list_of_floats = [3.596821, 2.423287, 5.9283237, 7.23894823]

result = [f'{item:.2f}' for item in list_of_floats]

print(' '.join(result))  # 👉️ 3.60 2.42 5.93 7.24

str.join 方法将一个可迭代对象作为参数并返回一个字符串,该字符串是可迭代对象中字符串的串联。

调用该方法的字符串用作元素之间的分隔符。

list_of_floats = [3.596821, 2.423287, 5.9283237, 7.23894823]

result = [f'{item:.2f}' for item in list_of_floats]

print(', '.join(result))  # 👉️ 3.60, 2.42, 5.93, 7.24