Search code examples
pythonlistmembership

Product of lists of lists with variable members


Say I have this input data

my_input_list = [[A],[A,B,C],[D],[D,E,F],[A,B,C,D,E,F],[A,C,E]]
items_that_appear_twice = [A,B,C]
items_that_appear_four = [D,E,F]

And I want to create an expansion such that some elements are only allowed to appear twice.

my_output_list = [
[A],[A],
[A,B,C],[A,B,C],
[D],[D],[D],[D],
[D,E,F],[D,E,F],[D,E,F],[D,E,F],
[A,B,C,D,E,F],[A,B,C,D,E,F],[D,E,F],[D,E,F],
[A,C,E],[A,C,E],[E],[E]]

I tired a few ideas and didn't find a really neat solution, like building lists of four and list.remove() from them which generated two empty lists. For example list removal techniques on my_input_list[0]*4 gives [A],[A],[],[] (two empty lists) when I want [A],[A] .


Solution

  • I have a working version: See Pyfiddle.

    my_input_list = [['A'],['A','B','C'],['D'],['D','E','F'],['A','B','C','D','E','F'],['A','C','E']]
    items_that_appear_twice = ['A','B','C']
    items_that_appear_four = ['D','E','F']
    
    my_output_list = []
    for my_input in my_input_list:
        items_allowed_to_appear_twice = list(filter(
            lambda value: (value in items_that_appear_twice 
                           or value in items_that_appear_four),
            my_input))
    
        items_allowed_to_appear_four = list(filter(
            lambda value: value in items_that_appear_four,
            my_input))
    
        my_output_list += 2*[items_allowed_to_appear_twice]
        if len(items_allowed_to_appear_four):
            my_output_list += 2*[items_allowed_to_appear_four]
    
    print(my_output_list)