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

标签 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))

我当前的代码只显示包含 5 个数字的一​​行,预期应该是 5 行,每行包含 5 个数字

最佳答案

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

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

print(*display(lx), sep='\n')

这个输出:

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

关于python - 如何从列表中每行显示 5 个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55661929/

相关文章:

python - 如何在普通 CGI 中区分 GET 和 POST

python - 按值重新格式化 pandas DataFrame 计数

Python 多处理 - 返回一个字典

python - 在Python中迭代大型文件目录系统,获取太多值而无法解压

python - 如何创建一个排序数组,其顺序与输入相关联

python - 多边形与圆的碰撞检测

python - 大型迭代器的笛卡尔积(itertools)

c++ - 使用 boost.python 将类暴露给 python 时出现构建错误

python - 我想创建一个函数,以 pythonic 方式通过 num 变量滚动一定数量的骰子

python - 属性错误: type object 'Team' has no attribute '_meta'