Home > database >  Pythonic way of "inner join" of list of lists with arbitrary lengths?
Pythonic way of "inner join" of list of lists with arbitrary lengths?

Time:08-31

I have an arbitrary list of lists, for example

x = [
        [5, 1, 2, 3, 4],
        [5, 6, 7, 8, 9],
        [5, 10, 11, 12]
    ]

There is only one element which is a member of all three lists in x = 5

My question: What is the most pythonic method of testing membership of elements in an arbitrary number of lists?

My solution is as follows, but feels like it could be simpler:

y = x[0]
if len(x) > 1:
    for subset in x[1:]:
        x = list(set(x) & set(subset))

CodePudding user response:

You can use functools.reduce to solve this problem:

functools.reduce(lambda y, z: y.intersection(set(z)), x, set)
# {5}

CodePudding user response:

Another, potentially more pythonic way of achieving this is:

results = [val for val in x[0] if all(val in ls for ls in x[1:])]

This creates a new list of all vals in the first sublist (x[0]) if the value is also in all lists (ls) in all other sublists (x[1:]).

This could be considered a more pythonic method as it uses only raw python, rather than say, using functools.reduce (as suggested in another answer).
It also demonstrates python's unique ability to create a list other list(s) based on a certain condition.

  • Related