Matrix Data Type Rectification in Python
Sometimes while giving data as an input we pass the numbers in string type. Later we come to know that we need the numbers in int or float type instead of a string. At this time the concept of rectification comes into the picture. This also happens when we are working on the matrix data. This rectification of the data type on the matrix data is known as Matrix Data Type Rectification.
There we will discuss the two types of rectification:
- Rectification using the list comprehension.
- Rectification using the map function.
# Method 1: List comprehension
Using list comprehension we will gonna check that is the element of the list ( i ) is a number or a string using isdigit() function.
# Python program in Python3 # Initialization of the list mix_list= [['CodeSpeedy','1'], ['21', '12'], ['is', '0'], ['the', '23'], ['7', 'best']] # Original list print(mix_list) # Matrix Data Type Rectification # isdigit() check whether the element is digit or not result_list = [[int(element) if element.isdigit() else element for element in i] for i in mix_list] #List Comprehension # required Result print (result_list)
Output:
[['CodeSpeedy', '1'], ['21', '12'], ['is', '0'], ['the', '23'], ['7', 'best']] [['CodeSpeedy', 1], [21, 12], ['is', 0], ['the', 23], [7, 'best']]
Method 2: Map function:
we will pass a lambda function which will check that the int(element) is a number or not, if it is a number then it will change the data type to int. Using map() function we will map the original list and a lambda function.
# Python program in Python3 # Initialization of the list mix_list= [['CodeSpeedy','1'], ['21', '12'], ['is', '0'], ['the', '23'], ['7', 'best']] # Original list print(mix_list) # Matrix Data Type Rectification # isdigit will check if is int(element) is digit or not #mapping of lambda function & original list result_list = [list(map(lambda element: int(element) if element.isdigit() else element, i)) for i in mix_list] # required Result List print (result_list)
Output:
[['CodeSpeedy', '1'], ['21', '12'], ['is', '0'], ['the', '23'], ['7', 'best']] [['CodeSpeedy', 1], [21, 12], ['is', 0], ['the', 23], [7, 'best']]
Leave a Reply