假设我有一个列表 [1,2,3,4,5,6]
,我想迭代 len 2 [1,2] 的所有子组[3,4] [5,6]
。
简单的做法
L = [1,2,3,4,5,6]
N = len(L)//2
for k in range(N):
slice = L[k*2:(k+1)*2]
for val in slice:
#Do things with the slice
但是我想知道是否有更Pythonic的方法来迭代“分区”列表。我也接受使用 numpy 数组的解决方案。像这样的东西:
L = [1,2,3,4,5,6]
slices = f(L,2) # A nice "f" here?
for slice in slices:
for val in slice:
#Do things with the slice
非常感谢!
最佳答案
使用grouper
来自 itertools
库的配方:
import itertools
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return itertools.zip_longest(*args, fillvalue=fillvalue)
L = [1,2,3,4,5,6]
for slice in grouper(L, 2):
print(slice)
关于python - 迭代列表的所有子组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74479111/