Home > Enterprise >  How to insert a newline in printing list in itertools
How to insert a newline in printing list in itertools

Time:11-01

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')]

CodePudding user response:

Unpack in print just like you already do in product...

for p in itertools.product(*s):
    print(*p)

CodePudding user response:

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,))))

CodePudding user response:

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)
  • Related