How to insert a newline in printing list in itertools

Question:

I am permuting a few list. How to print the result in a newline?

Code:

import itertools

s=[ [ '1', '2','3'], ['a','b'],
['4','5','6','7'],
    ['f','g','e','y']]

print (list(itertools.product(*s,)))

Need Result:

#-- with a newline

1 a 4 f 
1 a 4 g 
1 a 4 e 
1 a 4 y

Current Result:

#-- not very readable

[('1', 'a', '4', 'f'), ('1', 'a', '4', 'g'), ('1', 'a', '4', 'e'), ('1', 'a', '4', 'y')]
Asked By: errzoned

||

Answers:

You can unpack the tuples to f-strings, and join them all using n as a separator.

import itertools

s=[ ['1', '2','3'], 
    ['a','b'],
    ['4','5','6','7'],
    ['f','g','e','y'] ]

print('n'.join((f'{a} {b} {c} {d}' for a,b,c,d in itertools.product(*s,))))
Answered By: bn_ln

You could convert it to a dataframe and then call to_string()

import pandas as pd
import itertools
s=[ [ '1', '2','3'], ['a','b'],
['4','5','6','7'],
    ['f','g','e','y']]

df = pd.DataFrame(list(itertools.product(*s,)))

print(df.to_string(index=False))

If you don’t want the columns at the top do this

_, s = df.to_string(index=False).split('n', 1)
print(s)
Answered By: Ryno_XLI

Unpack in print just like you already do in product…

for p in itertools.product(*s):
    print(*p)
Answered By: Kelly Bundy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.