Python リストをバッチでループするにはどうすればいいですか? 質問する

Python リストをバッチでループするにはどうすればいいですか? 質問する

ファイルには 10000 行が含まれており、各行に 1 つのエントリがあります。ファイルをバッチ (小さなチャンク) で処理する必要があります。

file = open("data.txt", "r")
data = file.readlines()
file.close()

total_count = len(data) # equals to ~10000 or less
max_batch = 50 # loop through 'data' with 50 entries at max in each loop.

for i in range(total_count):
     batch = data[i:i+50] # first 50 entries
     result = process_data(batch) # some time consuming processing on 50 entries
     if result == True:
           # add to DB that 50 entries are processed successfully!
     else:
           return 0 # quit the operation
           # later start again from the point it failed.
           # say 51st or 2560th or 9950th entry

次のループで 51 番目から 100 番目の項目までのエントリが選択されるようにするには、ここで何をすればよいでしょうか?

何らかの理由で操作が成功せず、途中で中断した場合は、失敗したバッチからのみループを再開する必要があります (DB エントリに基づく)。

適切なロジックをコーディングできません。リストを 2 つ保持する必要がありますか? または、他に何かありますか?

ベストアンサー1

l = [1,2,3,4,5,6,7,8,9,10]
batch_size = 3    

for i in range(0, len(l), batch_size):
    print(l[i:i+batch_size])
    # more logic here

>>> [1,2,3]
>>> [4,5,6]
>>> [7,8,9]
>>> [10]

これは最も簡単で読みやすいアプローチだと思います。特定のバッチを再試行する必要がある場合は、ループ内で再試行するか (シリアル)、バッチごとにスレッドを開くことができます (アプリケーションによって異なります)。

おすすめ記事