Python – Extract Preceding Record from list values
Sometimes, while working with Tuple records, we can have a problem in which we need to extract the record, which is preceding to particular key provided. This kind of problem can have application in domains such as web development and day-day programming. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [(‘Gfg’, 3), (‘is’, 4), (‘best’, 1), (‘for’, 10), (‘geeks’, 11)], key = ‘geeks’
Output : (‘for’, 10)
Input : test_list = [(‘Gfg’, 3), (‘is’, 4), (‘best’, 1), (‘for’, 10), (‘geeks’, 11)], key = ‘is’
Output : (‘Gfg’, 3)
Method #1 : Using zip() + enumerate() + loop
The combination of above functions can be used to perform this particular task. In this, we create 2 lists, one with starting with next index. The zip(), helps to connect them and return the desired result using enumerate() for extracting index.
Python3
# Python3 code to demonstrate working of # Extract Preceding Record # Using zip() + enumerate() + loop # initializing list test_list = [( 'Gfg' , 3 ), ( 'is' , 4 ), ( 'best' , 1 ), ( 'for' , 10 ), ( 'geeks' , 11 )] # printing original list print ( "The original list is : " + str (test_list)) # initializing Key key = 'for' # Extract Preceding Record # Using zip() + enumerate() + loop for idx, (a, b) in enumerate ( zip (test_list, test_list[ 1 :])): if b[ 0 ] = = key: res = (a[ 0 ], a[ 1 ]) # printing result print ( "The Preceding record : " + str (res)) |
The original list is : [('Gfg', 3), ('is', 4), ('best', 1), ('for', 10), ('geeks', 11)] The Preceding record : ('best', 1)
Method #2 : Using list comprehension + enumerate()
The combination of above functions can be used to solve this problem. In this, we perform the task of extracting the previous element to manually test previous key, rather than creating a separate list as in previous method.
Python3
# Python3 code to demonstrate working of # Extract Preceding Record # Using list comprehension + enumerate() # initializing list test_list = [( 'Gfg' , 3 ), ( 'is' , 4 ), ( 'best' , 1 ), ( 'for' , 10 ), ( 'geeks' , 11 )] # printing original list print ( "The original list is : " + str (test_list)) # initializing Key key = 'for' # Extract Preceding Record # Using list comprehension + enumerate() res = [(test_list[idx - 1 ][ 0 ], test_list[idx - 1 ][ 1 ]) for idx, (x, y) in enumerate (test_list) if x = = key and idx > 0 ] # printing result print ( "The Preceding record : " + str (res)) |
The original list is : [('Gfg', 3), ('is', 4), ('best', 1), ('for', 10), ('geeks', 11)] The Preceding record : [('best', 1)]