在python中将列表输出为"矩阵"类型格式

jts*_*287 1 python

my_list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven']
Run Code Online (Sandbox Code Playgroud)

使用python,我需要将列表显示为:

one, two, three
four, five, six
seven
Run Code Online (Sandbox Code Playgroud)

我需要它灵活,因为列表会经常更改.

Mar*_*ers 7

您可以使用itertools中的石斑鱼配方:

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)
Run Code Online (Sandbox Code Playgroud)

使用这样:

for line in grouper(3, my_list):
    print ', '.join(filter(None, line))
Run Code Online (Sandbox Code Playgroud)

看到它在线工作:ideone