如何在itertools中的打印列表中插入换行符



我正在排列一些列表。如何在新行中打印结果?

代码:

import itertools
s=[ [ '1', '2','3'], ['a','b'],
['4','5','6','7'],
['f','g','e','y']]
print (list(itertools.product(*s,)))

需要结果:

#-- with a newline
1 a 4 f 
1 a 4 g 
1 a 4 e 
1 a 4 y

当前结果:

#-- not very readable
[('1', 'a', '4', 'f'), ('1', 'a', '4', 'g'), ('1', 'a', '4', 'e'), ('1', 'a', '4', 'y')]

像在产品中一样在打印中开箱。。。

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

您可以将元组解压缩为f-string,并使用n作为分隔符将它们全部连接起来。

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

您可以将其转换为数据帧,然后调用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))

如果你不想在顶部的列做这个

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

最新更新