如何从列表中每行显示5个数字?

Zek*_*ina 1 python

如何从列表中每行显示5个数字?

lx = [1,2,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25] 

def display(lx):

    for i in range(0,len(lx), 5):
        x = lx[i:i +5]
    return x

print(display(lx))
Run Code Online (Sandbox Code Playgroud)

我当前的代码仅显示一行包含5个数字的行,预期应为5行,每行包含5个数字

blh*_*ing 6

您可以通过使函数产生切片列表来使函数成为生成器:

def display(lx):
    for i in range(0, len(lx), 5):
        yield lx[i:i + 5]

print(*display(lx), sep='\n')
Run Code Online (Sandbox Code Playgroud)

输出:

[1, 2, 4, 5, 6]
[7, 8, 9, 10, 11]
[12, 13, 14, 15, 16]
[17, 18, 19, 20, 21]
[22, 23, 24, 25]
Run Code Online (Sandbox Code Playgroud)