Hướng dẫn python create multidimensional array

Hướng dẫn python create multidimensional array

Introduction to Multidimensional Arrays in Python

Multidimensional Array concept can be explained as a technique of defining and storing the data on a format with more than two dimensions (2D). In Python, Multidimensional Array can be implemented by fitting in a list function inside another list function, which is basically a nesting operation for the list function. Here, a list can have a number of values of any data type that are segregated by a delimiter like a comma. Nesting the list can result in creating a combination of values for creating the multidimensional array.

List

The list can be used to represent data in the below format in python:

List = [1, 2, 3]

The list can be written with comma-separated values. The list can have data such as integer, float, string, etc. and can be modified as well after creation. The indexing in lists is pretty straightforward, with the index starting from 0 and stretches until the whole length of list-1.

When a list has other lists in as elements, it forms a multidimensional list or array. For example:

List = [ [1, 2], [2,5], [5,1] ]

Here each value of the list can be accessed by writing the list name followed by a square bracket to retrieve the outer list values as below:

Print ( List[1] )

# [2, 5]

If you want to go further inside the inner list, add one more square bracket to access its elements as below:

Print ( List[1][0] )

# 2

Similarly, if we have multiple lists inside a list like:

List = [ [1, 3, 5], [8, 5, 6], [7, 1, 6] ] #can be also viewed as

| 1, 3, 5 |

| 8, 5, 6 |

| 7, 1, 6 |

All the elements of the list can be accessed by below indices:

[0][0], [0][1], [0][2] [1][0], [1][1], [1][2] [2][0], [2][1], [2][2]

Creating a Multidimensional List or Array

Let us suppose we have two variables: the numbers of rows ‘r’ and the number of columns ‘c’. hence to make a matrix of size m*n, it can be made as:

Array = [ [0] * c ] * r ] # with each element value as 0

This type of declaration will not create m*n spaces in memory; rather, only one integer will be created, which is referenced by each element of the inner list, whereas the inner lists are being put as elements in the outer list. Hence in such case, if we change any element to 5, then the whole array will have 5 as values in each element place of the same column as below:

Array[0][0] = 5

| 5, 0, 0 |

| 5, 0, 0 |

| 5, 0, 0 |

Another way to declare an Array is by using a generator with a list of ‘c’ elements repeated ‘r’ times. The declaration can be done as below:

c = 4
r = 3
Array = [ [0] * c for i in range(r) ]

Over here, each element is completely independent of the other elements of the list. The list [0] * c is constructed r times as a new list, and here no copying of references happens.

How to input values into Multidimensional Arrays?

Here we suppose a 2D array with r rows and c columns for which we will take the values of the elements from the user.

# User will enter the number of rows in the first line
r = int(input()) 
arr = []
for i in range(r):
    arr.append([int(j) for j in input().split()])

Iterating Values of a Multidimensional Array

In order to iterate through all the elements of the multidimensional array, we need to use the nested for loop concept as below:

# at first we will create an array of c columns and r rows
c = 4
r = 3
arr = [[0] * c for i in range(r)]
# loop will run for the length of the outer list
for i in range(r):
# loop will run for the length of the inner lists
    for j in range(c):
        if i < j: arr[i][j] = 8 elif i > j:
            arr[i][j] = 4
        else:
            arr[i][j] = 7
for r in arr:
    print( ' '.join([str(x) for x in r] ) )

Numpy Multidimensional Arrays

Let us see the numpy multimedia arrays in python:

Numpy is a pre-defined package in python used for performing powerful mathematical operations and support an N-dimensional array object. Numpy’s array class is known as “ndarray”, which is key to this framework. Objects from this class are referred to as a numpy array. The difference between Multidimensional and Numpy Arrays is that numpy arrays are homogeneous, i.e. it can contain an only integer, string, float, etc., values and their size are fixed. The multidimensional list can be easily converted to Numpy arrays as below:

import numpy as nmp
arr = nmp.array( [ [1, 0], [6, 4] ] )
print(arr)

Here the given multidimensional list is cast to Numpy array arr.

Creating a Numpy Array

import numpy as nmp
X = nmp.array( [ [ 1, 6, 7], [ 5, 9, 2] ] )
print(X)                                                  #Array of integers
X = nmp.array( [ [ 1, 6.2, 7], [ 5, 9, 2] ] )
print(X)                                                  #Array of floats
X = nmp.array( [ [ 1, 6, 7], [ 5, 9, 2] ], dtype = complex )
print(X)                                                  #Array of complex numbers

Output:

[[1 6 7] [5 9 2]] [[ 1.   6.2  7. ] [ 5.   9.   2. ]] [[ 1.+0.j  6.+0.j  7.+0.j] [ 5.+0.j  9.+0.j  2.+0.j]]

Accessing Numpy Matrix Elements, Rows and Columns

Each element of the Numpy array can be accessed in the same way as of Multidimensional List, i.e. array name followed by two square braces, which will tell the row and column index to pick a specific element.

Example:

import numpy as nmp
X = nmp.array( [ [ 1, 6, 7],
                 [ 5, 9, 2],
                 [ 3, 8, 4] ] )
print(X[1][2]) # element at the given index i.e. 2
print(X[0])     # first row
print(X[1])      # second row
print(X[-1])     # last row
print(X[:, 0])  # first column
print(X[:, 2])  # third column
print(X[:, -1]) # last column

Output:

2

[1 6 7] [5 9 2] [3 8 4] [1 5 3] [7 2 4] [7 2 4]

Some Properties of Numpy Array

Some basic properties of Numpy arrays are used in the below program:

import numpy as nmp
zero_array = nmp.zeros( (3, 2) )
print('zero_array = ',zero_array)
one_array = nmp.ones( (3, 2) )
print('one_array = ',one_array)
X = nmp.arange(9).reshape(3, 3)
print('X= ', X)
print('Transpose of X= ', X.transpose())

Output:
zero_array = [[0.  0.] [0.  0.] [0.  0.]] one_array = [[1.  1.] [1.  1.] [1.  1.]] X= [[0 1 2] [3 4 5] [6 7 8]] Transpose of X= [[0 3 6] [1 4 7] [2 5 8]]

Conclusion

Multidimensional arrays in Python provides the facility to store different type of data into a single array ( i.e. in case of the multidimensional list ) with each element inner array capable of storing independent data from the rest of the array with its own length also known as a jagged array, which cannot be achieved in Java, C, and other languages.

This is a guide to Multidimensional Arrays in Python. Here we discuss the Introduction to Multidimensional Arrays in Python, Creating a Multidimensional List or Array, etc. You can also go through our other suggested articles to learn more–

  1. C# Jagged Arrays
  2. 3D Arrays in Java
  3. Arrays in PHP
  4. C# Multidimensional Arrays