Python行列适配与格式调整技术问询:如何修改代码使行列匹配输入数字并呈现指定样式
Hey there! Let's work through your two main questions and fix your code to get the output you want.
1. Making Rows & Columns Adapt to Input Numbers (Plus Neat Alignment)
Your current code already loops through the input rows (num1) and columns (num2), but the output might look messy because the numbers aren't properly aligned. To fix this, use formatted strings to give each element a fixed width—this ensures columns line up neatly no matter how large your input numbers get.
Here's an updated version of your base code with clean alignment:
num1 = int(input("Enter number of rows: ")) num2 = int(input("Enter number of columns: ")) # Loop through each row for i in range(num1): # Loop through each column in the current row for j in range(num2): # Use f-string to format numbers with a 2-character fixed width print(f"{i:2d} {j:2d}", end=" ") # Move to a new line after finishing all columns in the row print()
Using {i:2d} means "print integer i in a 2-character wide space"—this keeps columns aligned even if you input larger row/column counts.
2. Adapting to Pattern1-Style Output (Numbers Arranged by Column)
Since you mentioned modifying a patterns1-style layout, I'll cover common column-based patterns you might be aiming for. Pick the one that matches your target image, or tweak it further if needed:
Pattern A: Each Column Displays Its Column Number
If you want every cell in column j to show the column's index (so values stay consistent down the column), adjust the inner loop to print j instead of both i and j:
num1 = int(input("Enter number of rows: ")) num2 = int(input("Enter number of columns: ")) for i in range(num1): for j in range(num2): print(f"{j:2d}", end=" ") print()
Sample Output (num1=3, num2=4):
0 1 2 3 0 1 2 3 0 1 2 3
Pattern B: Each Column Displays Its Row Number
If you want every cell in row i to show the row's index (so values stay consistent across the row), print i instead:
num1 = int(input("Enter number of rows: ")) num2 = int(input("Enter number of columns: ")) for i in range(num1): for j in range(num2): print(f"{i:2d}", end=" ") print()
Sample Output (num1=3, num2=4):
0 0 0 0 1 1 1 1 2 2 2 2
Custom Pattern (Matching Your Image)
If your target image has a different pattern (like diagonal sequences, increasing values, etc.), just adjust the expression inside the print() statement. For example, to show the sum of row and column indices:
print(f"{i+j:2d}", end=" ")
Sample Output (num1=3, num2=4):
0 1 2 3 1 2 3 4 2 3 4 5
If you can describe the exact style from your image (e.g., "each column starts at 1 and increments down the rows"), I can help refine this even more!
内容的提问来源于stack exchange,提问作者Maybeline Lee

