ython provides various built-in functions and modules to perform various tasks. Finding the minimum k records from a tuple list is one of the common tasks that can be easily achieved in Python. In this article, we will learn the different ways to find the minimum k records from a tuple list in Python.
Method 1: Using Sorted() Function
The sorted() function is a built-in function in Python that returns a sorted list from the elements of a given list. To find the minimum k records from a tuple list, we can use the sorted() function and return the first k elements of the sorted list.
def minimum_k_records(tuple_list, k): sorted_list = sorted(tuple_list, key = lambda x: x[1]) return sorted_list[:k] tuple_list = [('John', 45), ('Sarah', 25), ('Mike', 60), ('Jessica', 35)] k = 2 print(minimum_k_records(tuple_list, k))
Output :
[('Sarah', 25), ('Jessica', 35)]
Method #2 : Using sorted() + itemgetter()
The combination of above functions can also be used to perform this particular task. In this, the task performed by lambda function is performed by itemgetter() is used to get the index in tuple which has to be included in calculations.
# Python3 code to demonstrate working of # Minimum K records # Using sorted() + itemgetter() from operator import itemgetter # Initializing list test_list = [('Manjeet', 10), ('Akshat', 4), ('Akash', 2), ('Nikhil', 8)] # Initializing K K = 2 # printing original list print("The original list is : " + str(test_list)) # Minimum K records # Using sorted() + itemgetter() res = sorted(test_list, key = itemgetter(1))[:K] # printing result print("The lowest K records are : " + str(res))
Output :
The original list is : [('Manjeet', 10), ('Akshat', 4), ('Akash', 2), ('Nikhil', 8)] The lowest K records are : [('Akash', 2), ('Akshat', 4)]
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.