python - 迭代列表的所有子组

标签 python list numpy

假设我有一个列表 [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/

相关文章:

python - 连接两个 Pandas 数据框并重新排序列

用于识别文章主题的 python 库

python - 将一个真值表附加到另一个真值表

r - 从列表创建数据框

python - 在 numpy 中一次将函数应用于 3 个元素

python - 在 Numpy 中迭代的更多 pythonic 方式

python - 如何将 Google Analytics 添加到 reStructuredText?

javascript - 服务器端 python 返回 zip 文件以供下载

python - 使用元组 python 列表

python - 计算我的 for 循环,并希望使用某些函数在没有 for 循环的情况下进行计算