Combining sets/dictionaries

Peter Otten __peter__ at web.de
Tue Sep 22 07:04:48 EDT 2009


Alfons Nonell-Canals wrote:

> I have different sets/dictionaries/lists (whatever you want because I
> can convert them easily) and I would like to combine them. I don't want
> a consensus and something like it. I'd need to combine all elements of
> the first one with the all elements of the second one and third,... the
> numbers of dictionaries/sets/lists is variable as the number of elements
> for each one.
> 
> For example, i have the following sets and I would like to obtain all
> possible combinations...
> 
> ['I', 'O', 'N', 'P', 'S', 'C']
> ['I', 'O', 'N', 'P', 'S', 'C']
> ['I', 'O', 'N', 'P', 'S', 'C']
> ['I', 'N', 'P', 'S', 'C']
> ['I', 'N', 'P', 'S', 'C']
> ['F', 'I', 'L', 'O', 'N', 'P', 'S', 'R', 'C']
> ['I', 'O', 'N', 'P', 'S', 'C']
> ['I', 'O', 'N', 'P', 'S', 'C']
> ['F', 'I', 'L', 'O', 'N', 'P', 'S', 'R', 'C']
> 
> And it should be flexible because as I've said, the number of
> dictionaries/lists/sets is not always the same, as the number of elements.
> 
> I don't like to ask this kid of questions but... today I'm totally lost
> and I need it to close one part of a nice project...

Using one common definition of "combinations":

>>> from pprint import pprint
>>> pprint(items)
[['I', 'O', 'N', 'P', 'S', 'C'],
 ['I', 'O', 'N', 'P', 'S', 'C'],
 ['I', 'O', 'N', 'P', 'S', 'C'],
 ['I', 'N', 'P', 'S', 'C'],
 ['I', 'N', 'P', 'S', 'C'],
 ['F', 'I', 'L', 'O', 'N', 'P', 'S', 'R', 'C'],
 ['I', 'O', 'N', 'P', 'S', 'C'],
 ['I', 'O', 'N', 'P', 'S', 'C'],
 ['F', 'I', 'L', 'O', 'N', 'P', 'S', 'R', 'C']]
>>> import itertools
>>> for c in itertools.combinations(items, 2):
...     print c
...
(['I', 'O', 'N', 'P', 'S', 'C'], ['I', 'O', 'N', 'P', 'S', 'C'])
(['I', 'O', 'N', 'P', 'S', 'C'], ['I', 'O', 'N', 'P', 'S', 'C'])
(['I', 'O', 'N', 'P', 'S', 'C'], ['I', 'N', 'P', 'S', 'C'])
(['I', 'O', 'N', 'P', 'S', 'C'], ['I', 'N', 'P', 'S', 'C'])
<snip>

If you mean something else (likely) please give a more detailed description 
or provide some examples with both input and desired output.

Peter




More information about the Python-list mailing list