如何整齐打印邻接矩阵的列索引以提升矩阵可读性?
Hey, let's fix that messy column header alignment for your adjacency matrix! The issue right now is that printing column labels as a raw list doesn't account for varying digit lengths (like 1 vs. 12) and the default list formatting adds brackets/commas that throw off alignment. Here's a straightforward approach to get clean, perfectly aligned output:
Core Ideas to Fix Alignment
- Use a fixed width for all indices: First, calculate how many digits your largest vertex number has (e.g., if your vertices go up to 20, that's 2 digits). This becomes the standard width for every row and column label, so they all line up neatly.
- Format column headers as a single aligned string: Ditch the raw list print. Instead, format each column number to the fixed width, then join them with spaces—this removes messy brackets and ensures consistent spacing.
- Simplify row index printing: Replace your if/else check with a formatted string that automatically aligns row indices to the same fixed width as columns.
Modified Code with Clean Alignment
def generate_adjacency_matrix(vertices): size = len(vertices) # Create empty adjacency matrix matrix = [['.' for _ in range(size)] for _ in range(size)] # Fill matrix with connections (simplified loop) for row in vertices: for connected_vertex in vertices[row]: matrix[row][connected_vertex] = '1' # Calculate fixed width for all index labels max_width = len(str(size - 1)) # Print aligned column headers col_headers = [f"{num:>{max_width}}" for num in range(size)] print(' ' * max_width, ' '.join(col_headers)) # Print matrix with aligned row indices for i in range(size): print(f"{i:>{max_width}} {matrix[i]}")
Key Improvements Explained
- Simplified matrix filling: Instead of looping through every column to check for connections, we directly iterate over the connected vertices in your input dictionary—this is more efficient and cleaner.
- Uniform index width:
max_widthensures every label (whether 1-digit like 0 or 2-digit like 12) takes up the same amount of space. The:>{max_width}format specifier right-aligns numbers, which looks natural for indices. - Clean column headers: By joining formatted labels with spaces, we eliminate the list brackets and commas that were causing misalignment. The leading
' ' * max_widthensures the column headers line up perfectly with the row indices below.
Example Output Preview
For your input dictionary including vertex 20, the output will look something like this:
0 1 2 3 ... 20 0 ['1', '.', '.', '.', ..., '.'] 1 ['.', '.', '.', '.', ..., '.'] ... 20 ['.', '.', '.', '.', ..., '.']
内容的提问来源于stack exchange,提问作者Neistow
相关产品推荐
相关产品推荐

