Python从文件加载浮点矩阵时输出重复结果的问题求助
Let’s break down why your code is producing a repeated long list instead of the expected 3x4 matrix, then fix it step by step.
What’s Wrong with the Original Code?
Your code has two critical issues causing the unexpected output:
Reusing the same list for all rows
You initializePonce outside theiloop. Every time you appendPtoK, you’re adding a reference to the same list—not a copy. As you keep adding elements toPacross iterations, all entries inKupdate to reflect the growing list, resulting in three copies of the full 12-element array.Unsafe file handling and global variable dependencies
The file is opened but never closed, which can lead to resource leaks. Additionally, your function relies on global variables (M,P,K) instead of encapsulating logic, making it harder to debug and reuse.
Corrected Code
We’ll handle two common input formats for your matrix data:
Case 1: Each row is on a separate line in fer.txt
If fer.txt looks like this:
1 2 3 4 3 5 6 7 2 8 9 10
Use this code:
#!/usr/bin/env python def load_matrix(file_path): matrix = [] # Use 'with' to auto-close the file after reading with open(file_path, "r") as file: for line in file: # Split line into elements, convert to floats, add as a row row = list(map(float, line.strip().split())) matrix.append(row) return matrix # Load and print the matrix print(load_matrix("fer.txt"))
Case 2: All values are in a single line in fer.txt
If fer.txt has all 12 numbers in one line:
1 2 3 4 3 5 6 7 2 8 9 10
Use this code to split into 3 rows of 4 elements:
#!/usr/bin/env python def load_matrix(file_path): matrix = [] with open(file_path, "r") as file: # Read all values from the single line all_values = list(map(float, file.read().strip().split())) # Split into chunks of 4 elements (each row) for i in range(0, len(all_values), 4): row = all_values[i:i+4] matrix.append(row) return matrix # Load and print the matrix print(load_matrix("fer.txt"))
Expected Output
Both versions will produce the desired 3x4 matrix:
[[1.0, 2.0, 3.0, 4.0], [3.0, 5.0, 6.0, 7.0], [2.0, 8.0, 9.0, 10.0]]
Key Improvements:
- Encapsulated logic: The function takes a file path and returns the matrix without relying on global variables.
- Safe file handling: The
withstatement ensures the file is closed automatically. - Row isolation: Each row is a new list, so there’s no cross-reference between rows.
内容的提问来源于stack exchange,提问作者Layla

