逐步循环切片列表

Slice list in loop by step

寻找解决切片问题的好方法。

list_a = [1,2,3,4,5,6,7,8,9,10,11]
step = 5
print -> [1,2,3,4,5]
print -> [6,7,8,9,10]
print -> [11]

只需使用切片符号:list_a[:step]。使用 try 和 except: try: print(list_a[:step]) except: print('Out of Range')

这就是你想要做的:

output = [list_a[i:i + step] for i in range(0, len(list_a), step)]

当你通过时:

list_a = ['1','2','3','4','5','6','7','8','9','10']

你会得到这样的结果:

output = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'], ['10']]