python - 如何在 python for 循环中迭代多个元素

标签 python

<分区>

Possible Duplicate:
How do you split a list into evenly sized chunks in Python?

这个想法很简单,我想做这样的事情:

for elem1, elem2, elem3 in list:
    <some code>

为了让它工作,我们需要这个列表是一个 3-iterables 的列表,像这样:

list = [[1, 2, 3], [4, 5, 6]]

但是,如果这个列表只是一个常规列表,我该怎么办?

list = [1, 2, 3, 4, 5, 6]

是否有任何快速简单的方法可以将这个常规列表转换为 3-iterables 列表,以便循环可以工作?或 n-iterables,我在这里使用 3 作为示例。

谢谢。

最佳答案

使用 itertools 中的 grouper 配方:

def grouper(n, iterable, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

还有类似的东西:

for a, b, c in grouper(3, some_list):
    pass # whatever

关于python - 如何在 python for 循环中迭代多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14314985/

相关文章:

python - 创建多索引(3 轴)以取 1 轴的平均值

python - 如何从 django 中的低级缓存 API 中删除特定键

python - 根据 Pandas 多列中的值从数据框中选择行

Python 比已编译的 Haskell 更快?

python - OpenCV, cv2.approxPolyDP() 在闭合轮廓上绘制双线

python - 将python缩写的月份名称转换为全名

python - 错误: list index out of range

python - Cython:什么时候应该将字符串定义为 char*、str 或 bytes?

python - 如何在python中读取cookie

python - Pygame OpenGL 3D 立方体滞后