Custom length Matrix in Python

PythonServer Side ProgrammingProgramming

Sometimes when creating a matrix using python we may need to control how many times a given element is repeated in the resulting matrix. In this articled we will see how to create a matrix with required number of elements when the elements are given as a list.

Using zip

We declare a list with elements to be used in the matrix. Then we declare another list which will hold the number of occurrences of the element in the matrix. Using the zip function we can create the resulting matrix which will involve a for loop to organize the elements.

Example

 Live Demo

listA = ['m', 'n', 'p','q']

# Count of elements
elem_count = [1,0,3,2]

# Given Lists
print("Given List of elements: " ,listA)
print("Count of elements : ",elem_count)

# Creating Matrix
res = [[x] * y for x, y in zip(listA, elem_count)]

# Result
print("The new matrix is : " ,res)

Output

Running the above code gives us the following result −

Given List of elements: ['m', 'n', 'p', 'q']
Count of elements : [1, 0, 3, 2]
The new matrix is : [['m'], [], ['p', 'p', 'p'], ['q', 'q']]

with map and mul

In this approach we use the mul method from operator module in place of zip method above. Also the map function applies the mul method to every element in the list hence the for loop is not required.

Example

 Live Demo

from operator import mul

listA = ['m', 'n', 'p','q']

# Count of elements
elem_count = [1,0,3,2]

# Given Lists
print("Given List of elements: " ,listA)
print("Count of elements : ",elem_count)

# Creating Matrix
res = list(map(mul, listA, elem_count))

# Result
print("The new matrix is : " ,res)

Output

Running the above code gives us the following result −

Given List of elements: ['m', 'n', 'p', 'q']
Count of elements : [1, 0, 3, 2]
The new matrix is : ['m', '', 'ppp', 'qq']
raja
Published on 26-Aug-2020 06:56:11
Advertisements