Python将列表元素按指定个数分组小技巧

需求

将列表数据分为每五个一组,并遍历


写法1

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
n = 5
b = [a[i:i+n] for i in range(0,len(a),n)]
print(b) # [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12]]

for i in b:
    print(i)
    # [0, 1, 2, 3, 4]
    # [5, 6, 7, 8, 9]
    # [10, 11, 12]

写法2

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
n = 5
for b in [a[i:i + n] for i in range(0, len(a), n)]:
    print(b)
    # [0, 1, 2, 3, 4]
    # [5, 6, 7, 8, 9]
    # [10, 11, 12]
上一篇:hive union all报错


下一篇:mysql dba系统学习(18)mysql主从复制的实现