Syntax error Python program to extract rows from Matrix that has distinct data types

Python program to extract rows from Matrix that has distinct data types



When it is required to extract rows from a matrix with different data types, it is iterated over and ‘set’ is used to get the distinct types.

Example

Below is a demonstration of the same

my_list = [[4, 2, 6], ["python", 2, {6: 2}], [3, 1, "fun"], [9, (4, 3)]]

print("The list is :")
print(my_list)
my_result = []
for sub in my_list:

   type_size = len(list(set([type(ele) for ele in sub])))

   if len(sub) == type_size:
      my_result.append(sub)

print("The resultant distinct data type rows are :")
print(my_result)

Output

The list is :
[[4, 2, 6], ['python', 2, {6: 2}], [3, 1, 'fun'], [9, (4, 3)]]
The resultant distinct data type rows are :
[['python', 2, {6: 2}], [9, (4, 3)]]

Explanation

  • A list of different data types is defined and is displayed on the console

  • An empty list is defined.

  • The original list is iterated over, and the type of every element is determined.

  • It is converted into a set type, and then into a list.

  • Its size is determined, and it is compared with the specific size.

  • If they match, it is appended to the empty list.

  • This is displayed as output on the console.

Updated on: 2021-09-20T11:30:04+05:30

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements