简体   繁体   中英

Create 2D matrix using python

I have to create 2 x 3 matrix using python and every number has to increment

rows = int(input())
cols = int(input())

rows = 2
cols = 3
matrix = []
for i in range(rows):
    row = []
    i = 1
    for j in range(cols):
        i = i + 1
        row.append(i)
        
    matrix.append(row)

print(matrix)

my out is [[2, 3, 4], [2, 3, 4]]

if first number is 1 then [[1,2,3],[4,5,6]] every number has to increment

The mistake is that you are using the variable i for two things. One for your for-loop ( for i in... ) and as the value to be appended. Furthermore you are setting i=1 inside the loop, you want to initialize at the beginning. I have changed the name of the value to be appended to value :

rows = 2
cols = 3
matrix = []

value = 0
for i in range(rows):
    row = []
    for j in range(cols):
        value = value + 1
        row.append(value)
        
    matrix.append(row)

print(matrix)

Output: [[1, 2, 3], [4, 5, 6]]

I would suggest using Numpy to handle matrices and N-dimensional arrays in general. Your task can most easily be done with it:

import numpy as np

rows = int(input())
cols = int(input())

total = rows * cols + 1
matrix = np.arange(1, total).reshape((rows, cols))
print(matrix)

That being said, if you want pure Python you need to account for the current row: at row i the matrix already contains i * cols numbers!

rows = int(input())
cols = int(input())

rows = 2
cols = 3
matrix = []
for i in range(rows):
    row = []
    for j in range(cols):
        row.append(i * cols + j + 1)
        
    matrix.append(row)

print(matrix)

You can turn all of this in a comprehension list:

rows = int(input())
cols = int(input())
matrix = [[i * cols + j + 1 for j in range(cols)] for i in range(rows)]
print(matrix)

This gives you the output you're asking for:

import numpy as np
np.array([x for x in range(6)]).reshape((2,3))

Output:

array([[0, 1, 2],
       [3, 4, 5]])

If you need it to start at 1:

import numpy as np

np.array([x+1 for x in range(6)]).reshape((2,3))

Output:

array([[1, 2, 3],
       [4, 5, 6]])

Numpy might be an overkill for it, unless you are already planning to use numpy for other number processing.

Creating the nested list in ascending order is straightforward with list comprehensions. Suppose you want to have an initial value init :

rows, cols = 2, 3
init = 1
[[*range(r, r+cols)] for r in range(init, init+rows*cols, cols)]
# [[1, 2, 3], [4, 5, 6]]

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