久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

在Python中按(n)塊迭代迭代器?

Iterate an iterator by chunks (of n) in Python?(在Python中按(n)塊迭代迭代器?)
本文介紹了在Python中按(n)塊迭代迭代器?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!

問題描述

你能想出一個很好的方法(也許使用 itertools)來將迭代器分成給定大小的塊嗎?

Can you think of a nice way (maybe with itertools) to split an iterator into chunks of given size?

因此 l=[1,2,3,4,5,6,7]chunks(l,3) 成為迭代器 [1,2,3], [4,5,6], [7]

Therefore l=[1,2,3,4,5,6,7] with chunks(l,3) becomes an iterator [1,2,3], [4,5,6], [7]

我可以想到一個小程序來做到這一點,但可能不是使用 itertools 的好方法.

I can think of a small program to do that but not a nice way with maybe itertools.

推薦答案

itertools 文檔的 grouper() 配方.python.org/3/library/itertools.html#itertools-recipes" rel="nofollow noreferrer">recipes 接近你想要的:

The grouper() recipe from the itertools documentation's recipes comes close to what you want:

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

不過,它會用一個填充值填充最后一個塊.

It will fill up the last chunk with a fill value, though.

一種不太通用的解決方案,它只適用于序列,但可以根據(jù)需要處理最后一個塊

A less general solution that only works on sequences but does handle the last chunk as desired is

[my_list[i:i + chunk_size] for i in range(0, len(my_list), chunk_size)]

最后,一個適用于通用迭代器并按需要運行的解決方案是

Finally, a solution that works on general iterators and behaves as desired is

def grouper(n, iterable):
    it = iter(iterable)
    while True:
        chunk = tuple(itertools.islice(it, n))
        if not chunk:
            return
        yield chunk

這篇關(guān)于在Python中按(n)塊迭代迭代器?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!

【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!

相關(guān)文檔推薦

How to draw a rectangle around a region of interest in python(如何在python中的感興趣區(qū)域周圍繪制一個矩形)
How can I detect and track people using OpenCV?(如何使用 OpenCV 檢測和跟蹤人員?)
How to apply threshold within multiple rectangular bounding boxes in an image?(如何在圖像的多個矩形邊界框中應(yīng)用閾值?)
How can I download a specific part of Coco Dataset?(如何下載 Coco Dataset 的特定部分?)
Detect image orientation angle based on text direction(根據(jù)文本方向檢測圖像方向角度)
Detect centre and angle of rectangles in an image using Opencv(使用 Opencv 檢測圖像中矩形的中心和角度)
主站蜘蛛池模板: 国产日韩精品一区 | 欧美一级黄色网 | 国产999精品久久久 午夜天堂精品久久久久 | 亚洲黄色在线免费观看 | 精品国产一区二区久久 | 免费同性女女aaa免费网站 | 婷婷成人在线 | 精品中文字幕一区 | 国产乱码一二三区精品 | 亚洲精品久久久一区二区三区 | 久久综合伊人 | 日韩国产专区 | 日日干夜夜操 | 亚洲欧美在线一区 | 天天天久久久 | 亚洲a视频 | 国产成人精品一区二区三区网站观看 | 亚洲精品免费在线观看 | 欧美日韩亚洲系列 | 精品久久精品 | 国产羞羞视频在线观看 | 亚洲视频二区 | yiren22综合网成人 | 日韩精品四区 | 99免费看 | 亚洲精品国产a久久久久久 中文字幕一区二区三区四区五区 | 国产小视频在线观看 | 日韩国产一区二区三区 | 综合久久网 | 久在线| 99国产精品久久久久久久 | 精品欧美一区二区在线观看欧美熟 | 国产精品亚洲综合 | 麻豆一区二区三区精品视频 | 欧美精品v国产精品v日韩精品 | 操久久| 国产精品一二区 | 激情 婷婷 | 国产亚洲欧美在线 | 久久福利电影 | 亚洲精品久久久久久久久久久久久 |