You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python生成左对齐文本、小数点对齐且抑制小数值的列输出?

Yes, you can definitely generate that exact formatted output using Python! The main challenges here are aligning the text labels to the left and ensuring all float values line up perfectly at their decimal points, even when some have no fractional digits or are zero (including negative zeros).

While NumPy's np.set_printoptions is great for configuring array output, it doesn't seamlessly integrate text labels with decimal-aligned columns. Instead, we'll use custom string formatting to get full control over the layout. Here's a complete implementation:

import numpy as np
import math

def is_negative_zero(x):
    # Helper to distinguish negative zero from regular zero
    return x == 0.0 and math.copysign(1, x) == -1

def format_float_val(x):
    # Format individual float values to match the desired style
    if is_negative_zero(x):
        return '-0.'
    # Start with 5 decimal places
    formatted = f"{x:.5f}"
    # Strip trailing zeros after the decimal point
    formatted = formatted.rstrip('0')
    # Keep the decimal point even if there are no fractional digits left
    if '.' not in formatted:
        formatted += '.'
    return formatted

# Example input data (replace with your actual text and float arrays)
text_labels = [f'text{i+1}' for i in range(10)]
float_data = np.array([
    [-9.98442, -10., 0.01558],
    [-0., -0., 0.],
    [0., -0., -0.],
    [0.24829, 0.24829, -0.],
    [-7.40799, -7.40575, 0.00224],
    [0., -0., -0.],
    [-0., 0., 0.],
    [-5.88917, -5.83199, 0.05718],
    [-0., 0., 0.],
    [-6.83455, -6.74592, 0.08862]
])

# Step 1: Format all float values to their base string form
formatted_float_rows = [[format_float_val(num) for num in row] for row in float_data]

# Step 2: Align each column of floats by their decimal points
aligned_columns = []
# Transpose to process columns instead of rows
formatted_float_cols = list(zip(*formatted_float_rows))

for col in formatted_float_cols:
    split_parts = []
    max_int_length = 0
    # Split each value into integer and fractional parts, track longest integer section
    for s in col:
        int_part, frac_part = s.split('.', 1)
        split_parts.append((int_part, frac_part))
        if len(int_part) > max_int_length:
            max_int_length = len(int_part)
    # Pad integer parts to match the longest length, then recombine
    aligned_col = [f"{int_part.rjust(max_int_length)}.{frac_part}" for int_part, frac_part in split_parts]
    aligned_columns.append(aligned_col)

# Step 3: Format text labels (left-aligned with extra spacing)
max_text_len = max(len(text) for text in text_labels)
text_width = max_text_len + 2  # Add space between text and floats
formatted_texts = [f"{text:<{text_width}}" for text in text_labels]

# Step 4: Combine text and aligned floats into final lines
for text, col1, col2, col3 in zip(formatted_texts, aligned_columns[0], aligned_columns[1], aligned_columns[2]):
    print(f"{text}{col1} {col2} {col3}")

How This Works:

  1. Negative Zero Handling: The is_negative_zero helper ensures we display -0. instead of 0. for negative zero values (common in NumPy calculations).
  2. Float Formatting: Each float is first formatted to 5 decimal places, then trailing zeros are stripped to keep the output clean while retaining the decimal point.
  3. Decimal Alignment: For each column of floats, we split values into integer and fractional parts, find the longest integer section, then pad shorter integer parts with leading spaces so all decimal points line up.
  4. Text Alignment: Text labels are left-aligned with a fixed width to ensure they form a neat column.

Sample Output:

text1    -9.98442 -10.      0.01558
text2     -0.      -0.       0.
text3      0.      -0.      -0.
text4      0.24829   0.24829  -0.
text5    -7.40799  -7.40575  0.00224
text6      0.      -0.      -0.
text7     -0.       0.       0.
text8    -5.88917  -5.83199  0.05718
text9     -0.       0.       0.
text10   -6.83455  -6.74592  0.08862

This code is flexible—you can easily adjust the number of decimal places (change .5f to another number), the text width, or adapt it to work with regular Python lists instead of NumPy arrays.

内容的提问来源于stack exchange,提问作者Jonatan Öström

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:45:15