如何在Python中输入n定义n阶矩阵?现有代码无法实现该需求
Hey there! Let's get this sorted—your current code is only generating a one-dimensional list, which is why it can't create an n-order matrix (a 2D structure with n rows and n columns). Let's break down the problem and fix it.
First, let's recap your original code to see why it's not working:
num_array = list() num = input("Enter how many elements you want:") print('Enter numbers in array: ') for i in range(int(num)): n=input("num :") num_array.append(int(n)) print('ARRAY: ',num_array)
This code just shoves all your input numbers into a single list—so if you enter 4 for the number of elements, you get a list like [1,2,3,4] instead of a 2x2 matrix like [[1,2],[3,4]].
How to Make an n-Order Matrix
An n-order matrix is a list of lists: each sublist represents a row, and each row has exactly n elements. We'll use nested loops to build this structure step by step.
Working Code with Explanations
# Start with an empty matrix (this will hold our rows) matrix = [] # First, get the order of the matrix (n) n_input = input("Enter the order of your matrix (n): ") # Add quick validation to avoid crashes from bad input try: n = int(n_input) if n <= 0: print("Whoops, please enter a positive whole number!") exit() except ValueError: print("Oops, that's not a valid integer—try again!") exit() print(f"\nGreat! Now enter {n} numbers for each of the {n} rows:") # Build the matrix with nested loops for row_num in range(n): # Create an empty list for this row current_row = [] print(f"\nRow {row_num + 1}:") for col_num in range(n): element = input(f"Enter element {col_num + 1}: ") # Make sure the input is a number try: current_row.append(int(element)) except ValueError: print("That's not a valid number—let's start over!") exit() # Add the finished row to our matrix matrix.append(current_row) # Print the final matrix nicely print("\nHere's your n-order matrix:") for row in matrix: print(row)
What's Happening Here?
- The outer loop runs
ntimes—once for each row in the matrix. - For each row, we create a new empty list (
current_row) and use the inner loop to collectnelements for that row. - Once a row is full, we add it to the main
matrixlist. - We added input validation to handle cases where someone enters a non-integer or negative number, so your program won't crash unexpectedly.
A More Concise Version (List Comprehension)
If you prefer shorter code, you can use Python's list comprehension to do the same thing in fewer lines:
try: n = int(input("Enter the order of your matrix (n): ")) if n <= 0: raise ValueError except ValueError: print("Please enter a positive integer!") exit() # Use nested list comprehension to build the matrix matrix = [[int(input(f"Row {i+1}, Element {j+1}: ")) for j in range(n)] for i in range(n)] # Print the result print("\nYour n-order matrix:") for row in matrix: print(row)
This does exactly the same thing as the nested loop version—it's just a more compact way to write it.
内容的提问来源于stack exchange,提问作者Patrick Bro

