
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extract Rows from Matrix with Distinct Data Types in Python
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.
Advertisements