需求
将列表数据分为每五个一组,并遍历
写法1
写法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]
2023-10-28 10:37:52
需求
将列表数据分为每五个一组,并遍历
写法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]