Python Forum
itertools: combinations - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: itertools: combinations (/thread-9029.html)



itertools: combinations - Skaperen - Mar-18-2018

i'm looking over the various functions in itertools but i'm not finding what i need.

my use case is to take a list of lists of strings and iterate over the 2nd level to produce a list of the combination of strings. the incoming list might be:

[  ['foo','bar'], ['+','-'], ['corn','wheat','rice'] ]
the first 3 and last 3 iterations (in a list) would be:

[
['foo','+','corn'],
['bar','+','corn'],
['foo','-','corn'],
...
['bar','+','rice'],
['foo','-','rice'],
['bar','-','rice'],
]
the whole big list of 12 (in this example) lists is what would be returned. the generator version of this would do a yield of each iteration for a total of 12 yields. better code would be agnostic about what kind of data object or reference is used in place of the strings. i was trying to write this myself. maybe i should go back to that.


RE: itertools: combinations - stranac - Mar-18-2018

You're looking for itertools.product().
>>> import itertools
>>> for x in itertools.product(['foo', 'bar'], ['+', '-'], ['corn', 'wheat', 'rice']):
...     print(x)
...
('foo', '+', 'corn')
('foo', '+', 'wheat')
('foo', '+', 'rice')
('foo', '-', 'corn')
('foo', '-', 'wheat')
('foo', '-', 'rice')
('bar', '+', 'corn')
('bar', '+', 'wheat')
('bar', '+', 'rice')
('bar', '-', 'corn')
('bar', '-', 'wheat')
('bar', '-', 'rice')



RE: itertools: combinations - Skaperen - Mar-19-2018

the order is different, but that's ok. itertools.product cycles the last list faster and my example cycles the first list faster. for my needs, it doesn't matter.