搜尋
首頁後端開發Python教學如何在 Python 中有效地對迭代器進行分塊?

How Can I Efficiently Chunk an Iterator in Python?

以區塊的形式迭代迭代器

考慮一個場景,您擁有一個迭代器l = [1, 2, 3, 4 , 5, 6 , 7] 並希望將其劃分為大小為3 的區塊,從而產生一個包含[[1, 2, 3], [4, 5, 6], [7]].

itertools 解決方案

Python 標準庫在itertools 模組中提供了一個方便的解決方案:

import itertools

def grouper(iterable, n, *, incomplete='fill', fillvalue=None):
    """Collect data into non-overlapping fixed-length chunks or blocks."""

    args = [iter(iterable)] * n
    if incomplete == 'fill':
        return zip_longest(*args, fillvalue=fillvalue)
    elif incomplete == 'strict':
        return zip(*args, strict=True)
    elif incomplete == 'ignore':
        return zip(*args)
    else:
        raise ValueError('Expected fill, strict, or ignore')

chunks = list(grouper(l, 3))  # Output: [[1, 2, 3], [4, 5, 6], [7]]

標準庫增強版本

在itertools 配方的最新版本中引入的批次專用函數,精確地滿足了這種分塊要求:

from itertools import batched

chunks = list(batched(l, 3))  # Output: [[1, 2, 3], [4, 5, 6], [7]]

非通用解決方案

特別是對於序列,一種更簡單的方法可以有效地處理最後的區塊是:

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

以上是如何在 Python 中有效地對迭代器進行分塊?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
您可以使用Python中的循環加入列表嗎?您可以使用Python中的循環加入列表嗎?May 10, 2025 am 12:14 AM

是的,YouCanconCatenatElistsusingAloopInpyThon.1)使用eparateLoopsForeachListToAppendIteMstoaresultList.2)useanestedlooptoiterateOverMultipliplipliplipliplipliplipliplipliplipliplistforamoreConciseApprace.3)

condenate列表python:使用,擴展()等condenate列表python:使用,擴展()等May 10, 2025 am 12:12 AM

ThemostefficientmethodsforconcatenatinglistsinPythonare:1)theextend()methodforin-placemodification,2)itertools.chain()formemoryefficiencywithlargedatasets.Theextend()methodmodifiestheoriginallist,makingitmemory-efficientbutrequirescautionifpreserving

Python循環:示例和最佳實踐Python循環:示例和最佳實踐May 10, 2025 am 12:05 AM

pythonboopsincludeforandwhileloops,with forloopsidealforequencessand and whileloopsforcondition repetition.bestpracticesinvolve:1)使用listComprehensionsforshensionsforsimpletranspletransformations,2)obseringEnumerateForIndex-valuepairs,3)optingftingftingfortermornemoremoremoremore

Python的執行模型:編譯,解釋還是兩者?Python的執行模型:編譯,解釋還是兩者?May 10, 2025 am 12:04 AM

pythonisbothCompileDIntered。

Python是按線執行的嗎?Python是按線執行的嗎?May 10, 2025 am 12:03 AM

Python不是嚴格的逐行執行,而是基於解釋器的機制進行優化和條件執行。解釋器將代碼轉換為字節碼,由PVM執行,可能會預編譯常量表達式或優化循環。理解這些機制有助於優化代碼和提高效率。

python中兩個列表的串聯替代方案是什麼?python中兩個列表的串聯替代方案是什麼?May 09, 2025 am 12:16 AM

可以使用多種方法在Python中連接兩個列表:1.使用 操作符,簡單但在大列表中效率低;2.使用extend方法,效率高但會修改原列表;3.使用 =操作符,兼具效率和可讀性;4.使用itertools.chain函數,內存效率高但需額外導入;5.使用列表解析,優雅但可能過於復雜。選擇方法應根據代碼上下文和需求。

Python:合併兩個列表的有效方法Python:合併兩個列表的有效方法May 09, 2025 am 12:15 AM

有多種方法可以合併Python列表:1.使用 操作符,簡單但對大列表不內存高效;2.使用extend方法,內存高效但會修改原列表;3.使用itertools.chain,適用於大數據集;4.使用*操作符,一行代碼合併小到中型列表;5.使用numpy.concatenate,適用於大數據集和性能要求高的場景;6.使用append方法,適用於小列表但效率低。選擇方法時需考慮列表大小和應用場景。

編譯的與解釋的語言:優點和缺點編譯的與解釋的語言:優點和缺點May 09, 2025 am 12:06 AM

CompiledLanguagesOffersPeedAndSecurity,而interneterpretledlanguages provideeaseafuseanDoctability.1)commiledlanguageslikec arefasterandSecureButhOnderDevevelmendeclementCyclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesandentency.2)cransportedeplatectentysenty

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境