简体   繁体   中英

Trouble filling an empty matrix in python

I have an array that was generated from records that contain [key, character]

I have a function that creates an empty matrix whose dimensions are determined by the size of the array and the width of the array. I need to populate this list using the characters from the first array. Right now when I compile this I just get None . Is there any way I can accomplish this different

def createArray(size):
    return [None] * size

def createMatrix(rows,cols):
    m = createArray(rows)
    for i in range(rows):
        m[i] = createArray(cols)
    return m

def fillMatrix(matrix, array):
    rows = len(matrix)
    cols = len(matrix[0])

    arrSpot = 0
    for r in range(0,rows,1):
        for c in range(0, cols, 1):
            matrix[r][c] = array[arrSpot][1]
            arrSpot += 1
    return

我认为您只是忘了给fillMatrix一个返回值。

A fairly simple way to do this would be to append rows as you go to a list. So, something like this:

def create_matrix(rows, cols):
  matrix = []
  for i in range(rows):
    row = [0]*cols
    matrix.append(row)
  return matrix

I would typically just use numpy for this. If you have numpy, then you can just do

import numpy as np
matrix = np.zeros((rows,cols))

(Note that the input to np.zeros is a tuple, not two arguments.)

dimension1 = int(input("Give the dimension of the row: "))
dimension2 = int(input("Give the dimension of the column: "))
matrix = [[0 for i in range(dimension1)] for j in range(dimension2)]
for y in range(dimension2):
    for x in range(dimension1):
        matrix[y][x] = int(input("next value starting from (0,0) to (0,1) to at 
        last(dimension1,dimension2) : "))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM