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

Python从文件加载浮点矩阵时输出重复结果的问题求助

Fixing the Repeated Matrix Issue in Your Python Code

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:

  1. Reusing the same list for all rows
    You initialize P once outside the i loop. Every time you append P to K, you’re adding a reference to the same list—not a copy. As you keep adding elements to P across iterations, all entries in K update to reflect the growing list, resulting in three copies of the full 12-element array.

  2. 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 with statement 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:22:02