[Tutor] Need help combining elements of a list of lists
steve at pearwood.info
Tue Jul 10 23:09:39 EDT 2018
On Tue, Jul 10, 2018 at 09:46:57PM -0500, Jim wrote:
> Say I have a list like ltrs and I want to print out all the possible 3
> letter combinations. I want to combine letters from each inner list but
> not combine any letters within the inner list itself. So ACF and ADF
> would be ok but ABC would not.
> I can lay it out manually and see the pattern, I cannot figure out how
> to do it programically. Just in case this looks like homework it is not.
> It's a small test case I devised to try to figure it out so I can apply
> it to a bigger real world problem I am working on.
> ltrs = [['A', 'B'], ['C', 'D', 'E'], ['F', 'G', 'H', 'I']]
If you know that there are just three sublists, then you can do this:
for a in ltrs:
for b in ltrs:
for c in ltrs:
print(a + b + c)
I trust that's easy enough to understand.
But here's a more general technique, where you don't need to know up
front how many nested lists there are:
from itertools import product # short for "Cartesian Product"
for s in product(*ltrs):
The *ltrs syntax might be a bit mysterious: it is called "sequence
unpacking", and tells the interpreter to use each item from ltrs as a
=> product(ltrs, ltrs, ltrs)
More information about the Tutor