Python – Like Index Common characters
Last Updated :
09 Apr, 2023
Sometimes we come across this type of problem in which we require to intersect each element of one list with the other. This type of problems usually occurs in developments in which we have the combined information, like names and surnames in different lists. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + zip() + intersection() List comprehension does the task of intersecting the similar index elements. The task of zip function is concatenating the resultant string into a single list and return list.
Python3
test_list1 = ["Geeksfor", " is ", "be"]
test_list2 = [ 'Geeks' , 'sb' , 'ste' ]
print ("The original list 1 is : " + str (test_list1))
print ("The original list 2 is : " + str (test_list2))
res = ["".join( list ( set (i).intersection( set (j)))) for i, j in zip (test_list1, test_list2)]
print ("The list after element intersection is : " + str (res))
|
Output :
The original list 1 is : ['Geeksfor', 'is', 'be']
The original list 2 is : ['Geeks', 'sb', 'ste']
The list after element intersection is : ['sGek', 's', 'e']
Time complexity: O(m*n), because it performs the same number of iterations as the original code.
Auxiliary space: O(m*n) as well, because it creates a dictionary with m * n keys and a list of m * n elements
Method #2 : Using map() + lambda + zip() + intersection() The task of mapping each index element with each other is performed by map function in this method and the functionality of intersection is performed by lambda and intersection() function. This method works only in Python 2.
Python3
test_list1 = ["Geeksfor", " is ", "be"]
test_list2 = [ 'Geeks' , 'sb' , 'ste' ]
print ("The original list 1 is : " + str (test_list1))
print ("The original list 2 is : " + str (test_list2))
res = list ( map ( lambda (i, j): "".join( list ( set (i).intersection( set (j)))), zip (test_list1, test_list2)))
print ("The list after element intersection is : " + str (res))
|
Output :
The original list 1 is : ['Geeksfor', 'is', 'be']
The original list 2 is : ['Geeks', 'sb', 'ste']
The list after element intersection is : ['sGek', 's', 'e']
Time complexity: O(m*n), because it performs the same number of iterations as the original code.
Auxiliary space: O(m*n) as well, because it creates a dictionary with m * n keys and a list of m * n elements
Share your thoughts in the comments
Please Login to comment...