ash94
ash94

Reputation: 21

Changing the output of this python code in to a list?

The following python code gives me the different combinations from the given values.

import itertools

iterables = [ [1,2,3,4], [88,99], ['a','b'] ]
for t in itertools.product(*iterables):
    print t

Output:-

(1, 88, 'a')
(1, 88, 'b')
(1, 99, 'a')
(1, 99, 'b')
(2, 88, 'a')

and so on.

Can some one please tell me how to modify this code so the output looks like a list;

188a
188b
199a
199b
288a

Upvotes: 2

Views: 66

Answers (2)

Ajax1234
Ajax1234

Reputation: 71471

You can try this:

iterables = [ [1,2,3,4], [88,99], ['a','b'] ]

new_list = [''.join(map(str, i)) for i in itertools.product(*iterables)]

Upvotes: 5

Martijn Pieters
Martijn Pieters

Reputation: 1124988

You'll have to convert the numbers to strings, then join the results:

print ''.join(map(str, t))

You could avoid having to convert if you made your inputs strings to begin with:

iterables = [['1', '2', '3', '4'], ['88', '99'], ['a', 'b']]
for t in itertools.product(*iterables):
    print ''.join(t)

If all you want is to print the values together (and not do anything with them otherwise) then use print() as a function (by using the from __future__ import print_function Python 2 feature switch or by using Python 3):

from __future__ import print_function

iterables = [[1, 2, 3, 4], [88, 99], ['a', 'b']]
for t in itertools.product(*iterables):
    print(*t)

Upvotes: 5

Related Questions