-2

Is it possible to compare a list containing an unknown number of lists with equal elements in a more terse (aka shorter) manner than what I have done? Preferably an one-liner!

Here's an example if it's unclear what I want to do:

a = [1, 2, 3]
b = [4, 2, 1]
c = [7, 5, 1]
d = [a, b, c]

def multiCompList(lists):
    final = [i for i in lists[0] if i in lists[1]]
    for i in range(2, len(lists)):
        final = [i for i in final if i in lists[i]]

    return final

print(multiCompList(d))

What I've done is to first check if the first and second list contains any equal elements and put them in a list called final. Thereafter, checking if those elements can be found in the lists after and replacing the final-list with the remaining equal elements. The results in this case is: [1].

5
  • you want to find the intersection of all the lists? does the order matter? Commented Oct 31, 2018 at 15:43
  • @Chris_Rands No I guess intersection of first two lists and third to nth list intersection. So not mere intersection of all the list Commented Oct 31, 2018 at 15:44
  • 1
    Perhaps you can apply your learning from here stackoverflow.com/questions/3852780/… Commented Oct 31, 2018 at 15:45
  • You sample example and explanation is tangential. DO u want to get common values from all the lists? Commented Oct 31, 2018 at 15:54
  • Thank you @RahulChawla. Exactly what I was looking for! Commented Oct 31, 2018 at 15:56

1 Answer 1

0

A oneliner would look like this:

set.intersection(*[set(x) for x in d])
#set([1])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.