Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find minimum k records from tuple list in Python
When it is required to find the minimum k records from a list of tuples, it can be done using the sorted() method and lambda function.
The sorted() method is used to sort the elements of a list. Anonymous function is a function which is defined without a name.
In general, functions in Python are defined using def keyword, but anonymous function is defined with the help of lambda keyword. It takes a single expression, but can take any number of arguments. It uses the expression and returns the result of it.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
A list of tuple basically contains tuples enclosed in a list.
Below is a demonstration of the same ?
Example
my_list = [(67, 'Will'), (34, 'Mark'), (99, 'Dev'), (2, 'Paul')]
print("The list is:")
print(my_list)
K = 3
print("The value of 'K' has been initialized")
my_result = sorted(my_list, key=lambda x: x[1])[:K]
print("The lowest " + str(K) + " records are:")
print(my_result)
Output
The list is: [(67, 'Will'), (34, 'Mark'), (99, 'Dev'), (2, 'Paul')] The value of 'K' has been initialized The lowest 3 records are: [(99, 'Dev'), (34, 'Mark'), (2, 'Paul')]
Finding Minimum k Records by Numeric Value
You can also find minimum k records based on numeric values (first element of tuple) ?
my_list = [(67, 'Will'), (34, 'Mark'), (99, 'Dev'), (2, 'Paul')]
print("The list is:")
print(my_list)
K = 2
print("Finding lowest", K, "records by numeric value")
my_result = sorted(my_list, key=lambda x: x[0])[:K]
print("The lowest " + str(K) + " records by number are:")
print(my_result)
The list is: [(67, 'Will'), (34, 'Mark'), (99, 'Dev'), (2, 'Paul')] Finding lowest 2 records by numeric value The lowest 2 records by number are: [(2, 'Paul'), (34, 'Mark')]
How It Works
- A list of tuples is defined, and displayed on the console.
- The value of
Kis initialized. - The
sorted()method is used to sort the list of tuples, based on the lambda function which is defined inside it. - The lambda function
key=lambda x: x[1]sorts by the second element (string), whilekey=lambda x: x[0]sorts by the first element (number). - Slicing
[:K]returns only the first K elements from the sorted list. - This result is displayed on the console.
Conclusion
Use sorted() with lambda functions to find minimum k records from tuple lists. Sort by different tuple elements using key=lambda x: x[index] and slice with [:K] to get the desired number of minimum records.
