Home > Back-end >  How to merge multiple lists into 1 but only those elements that were in all of the initial lists?
How to merge multiple lists into 1 but only those elements that were in all of the initial lists?

Time:12-28

I need to merge 5 lists of which any list can be empty that way so that only items that were in all 5 initial lists are included in the newly formed list.

for filter in filters:

    if filter == 'M':
        filtered1 = [] # imagine that this is filled

    if filter == 'V':
        filtered2 = [] # imagine that this is filled

    if filter == 'S':
        filtered3 = [] # imagine that this is filled

    if filter == 'O':
        filtered4 = [] # imagine that this is filled

    if filter == 'C':
        filtered5 = [] # imagine that this is filled

filtered = [] # merge all 5 lists from above

So now I need to make a list filtered with merged data from all filtered lists 1-5. How should I do that?

CodePudding user response:

Given some lists xs1, ..., xs5:

xss = [xs1, xs2, xs3, xs4, xs5]
sets = [set(xs) for xs in xss]
merged = set.intersection(*sets)

This has the property that merged may be in any order.

CodePudding user response:

This is the most classical solution.

filtered = filter1   filter2   filter3   filter4   filter5

What happens is that you add an list to another one and so on...

So if filter1 was ['a', 'b'] and filter3 was ['c', 'd'] and filter4 was ['e'], then you would get:

filtered = ['a', 'b', 'c', 'd', 'e']

CodePudding user response:

f1, f2, f3, f4, f5 = [1], [], [2, 5], [4, 1], [3]

only_merge = [*f1, *f2, *f3, *f4, *f5]
print("Only merge: ", only_merge)

merge_and_sort = sorted([*f1, *f2, *f3, *f4, *f5])
print("Merge and sort: ", merge_and_sort)

merge_and_unique_and_sort = list({*f1, *f2, *f3, *f4, *f5})
print("Merge, unique and sort: ", merge_and_unique_and_sort)

Output:

Only merge:  [1, 2, 5, 4, 1, 3]
Merge and sort:  [1, 1, 2, 3, 4, 5]
Merge, unique and sort:  [1, 2, 3, 4, 5]
  • Related