Method # 1: Using reduce () + lambda + set ()
This particular task can be achieved in one line using a combination of the above functions. The decrease function can be used to control the "& amp;" for the whole list. The set function can be used to convert a list to a set to remove duplicates.
# Python3 demo code # general form of extracting elements from N lists # using Reduce () + Lambda + Set () from functools import reduce # initializing the list of lists test_list = [[[ 2 , 3 , 5 , 8 ], [ 2 , 6 , 7 , 3 ], [ 10 , 9 , 2 , 3 ]] # print original list print ( " The original list is: " + str (test_list) ) # general form for extracting elements from N lists # using Reduce ( ) + Lambda + Set () res = list ( reduce ( lambda i, j: i & amp; j, ( set (x) for x in test_list))) # print result print ( "The common elements from N lists:" + str (res)) |
Exit:
The original list is: [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2 , 3]] The common elements from N lists: [2, 3]
Method # 2: Using map () + intersection ()
The map
function can be used to transform each of the lists into sets that need to be manipulated to perform the intersection using the set.intersection function. This is the most elegant way to accomplish this particular task.
# Python3 demo code # general form for extracting elements from N lists # using map () + intersection () # initializing the list of lists test_list = [[ 2 , 3 , 5 , 8 ], [ 2 , 6 , 7 , < / code> 3 ], [ 10 , 9 , 2 , 3 ]] # print original list print ( "The original list is:" + str (test_list)) # general form of extracting elements from N lists # using map () + intersection () res = list ( se t . intersection ( * map ( set , test_list))) # print result print ( "The common elements from N lists:" + str (res)) |
Exit:
The original list is: [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]] The common elements from N lists: [2, 3]