Search code examples
pythonpython-3.xpython-itertools

How to get all combinations from multiple lists with additional filtering?


a = [[1,2,3,4],[2,3,4,5],[5,6,7,8],[4,3,2,3]]
output: (1,2,5,4),(1,2,5,3),(1,2,5,2)...

I have multiple lists that I'm trying to find all possible combinations of that's similar to the above code. However due to the amount of lists and the amount of items in the list, my computer can't process it. So I was wondering if there was a way I could filter some combinations out by adding all the items(numbers) together. ex: (1,2,5,4) = 12; And then if that list total is under 15 then delete that list and move on to the next combination. I would have to do something like this anyway after I got all the combinations so I figured why not do it earlier.

My code which generates all possible combinations:

list(itertools.product(*a))

Any ideas on how I can implement this filtering concept?


Solution

  • You can use a list comprehension:

    from itertools import product
    
    a = [[1,2,3,4],[2,3,4,5],[5,6,7,8],[4,3,2,3]]
    
    l = [e for e in product(*a) if sum(e) > 15]
    

    However be aware that the generation of the initial products might be the bottleneck. If you have too many elements (only 256 in your example) there is a possibility that your computer can never generate them all, and the filtering won't change anything.