【问题标题】:Reshape matrix from .txt file从 .txt 文件重塑矩阵
【发布时间】:2021-04-22 10:41:10
【问题描述】:

我的这段代码采用.txt,其整数格式如下:

3 7 12  90 11
4   87  103 1 15 23 72 3
8   2
10
65 34 18 29

我想编写一个函数,根据用户提示的大小将其重塑为矩阵,并且给定的矩阵大小大于元素的数量,它会返回一条消息。

但我无法输入文件的整数,或者我不知道如何

例如:

如果您尝试将其重塑为 4 x 6 矩阵,您应该会收到如下消息:

Cannot reshape matrix: not enough matrix elements

并保持文件不变。

文件的新内容,重新调整为 3 x 6 矩阵,将是:

size 4 by 6
 
3712 9011
4 87 10311523723 82
10
65 34 18 29
  
3 7 12 90 11 4 
87 103 1 15 23 72 
3 8 2 10 65 34
#the numbers would be separated by "\t"

到目前为止,我只有这个,我被困住了。我不能使用像 Numpy 这样的导入。

def reshape (nCols, nRows, file):
    matrixSize = int(nCols*nRows)
    count = 0
    matrix = []
    total_numbers = 0
    for line in file :
        parts = line.split()
        total_numbers += len(parts)
    if matrixSize > total_numbers:
        return print("Not enough elements in the matrix")
    else:
        for i in range(0, nRows):
            while len(matrix)> 0: matrix.pop()
            for i in range(count, count+nCols):
                matrix.append(i)
                count+=1
            print(matrix)




getColInteger= int(input("Enter column integer size: "))
getRowsInteger = input("Enter rows integer size: ")
openFile = open("mat.txt", "r+")
toGetReshape = reshape(getColInteger, getRowsInteger, openFile)

【问题讨论】:

    标签: python python-3.x list function


    【解决方案1】:

    您可以创建一个包含所有数字的列表并将每个数字添加到矩阵中。

    查看以下代码:

    def reshape (nCols, nRows, file):
        matrixSize = int(nCols*nRows)
        count = 0
        matrix = []
        numbers = []
        numbers = []
        [numbers.extend(line.strip().split()) for line in file]
        total_numbers = len(numbers)
        if matrixSize > total_numbers:
            return print("Not enough elements in the matrix")
        else:
            for i in range(0, nRows):
                while len(matrix)> 0: matrix.pop()
                for i in range(count, count+nCols):
                    matrix.append(numbers[i])
                    count+=1
                print(matrix)
    
    getColInteger= int(input("Enter column integer size: "))
    getRowsInteger = int(input("Enter rows integer size: "))
    openFile = open("test.txt", "r+")
    toGetReshape = reshape(getColInteger, getRowsInteger, openFile)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-16
      • 1970-01-01
      • 2019-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多