開始使用免費開始

定義用於分塊的函式

為了能以可重現的方式批次 upsert,你需要定義一個函式,把向量清單切成多個區塊。

內建的 itertools 模組已經幫你匯入。

本練習屬於課程

使用 Pinecone 構建 AI 應用

檢視課程

練習說明

  • 將輸入的 iterable 轉成疊代器。
  • 使用 itertools 模組,將 itbatch_size 的大小切成多個區塊。
  • 產出(yield)目前的區塊。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

def chunks(iterable, batch_size=100):
    """A helper function to break an iterable into chunks of size batch_size."""
    # Convert the iterable into an iterator
    it = ____
    # Slice the iterator into chunks of size batch_size
    chunk = tuple(itertools.____(it, ____))
    while chunk:
        # Yield the chunk
        ____
        chunk = tuple(itertools.islice(it, batch_size))
編輯並執行程式碼