Skip to main content
Ask the question clearly in the title
Link
Karl Knechtel
  • 61.6k
  • 14
  • 135
  • 195

I'm looking for a way to combine multiple How can I get Cartesian products of some subsets of my lists in Python (itertools.product is very close to what I'm trying to do), as well as the product of the entire list of lists?

Source Link

I'm looking for a way to combine multiple lists in Python (itertools.product is very close to what I'm trying to do)

It's probably on Google, but I'm having a hard time putting into words what I'm trying to do. itertools.product is close, but I also want it to give me smaller combinations whereas itertools only gives combinations across all lists. It would probably be easier to explain in an example:

Example of lists I want to combine: [[a,b,c],[d,e,f],[g,h,i]]

Itertools gives back: [a,d,g],[a,d,h]....[c,f,h],[c,f,i] (27 results)

Output I am looking for: The above, plus:

[a,d],[a,e],[a,f],[b,d],[b,e],[b,f],[c,d],[c,e],[c,f],[d,g],[d,h],[d,i],[e,g],[e,h],[e,i],[f,g],[f,h],[f,i]

There would be a total of 45 results. Note that I'm only looking for combinations between the lists that are next to each other (don't want [a,g] returned). The lists will not be this simple either, there will be a set of 10 lists with 3-4 characters each.

The only line of code I have for this is: list(itertools.product(*thelist))]. I just don't know where to go next on what I'm trying to do here. I have a feeling there's some way to do this with itertools, I just can't figure it out.