You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python生成器实操:每次调用next()返回多行/多个点的实现方法

Hey there! Let's work through your problem—since you're new to Python generators, we'll keep this clear and practical.

First, let's address your core request: modifying your generator to return 5 points at a time instead of one. Plus, this approach will also answer your first question about returning multiple lines/data per next() call in general.

Step 1: Refine the Base Point Generator

First, let's tweak your original generator to use a with statement (this is a Python best practice—it automatically closes the file for you, even if something goes wrong). We'll also add a check for empty lines to make the code more robust:

import itertools

def gen_points(name):
    # Use `with` to handle file opening/closing automatically
    with open(name) as f:
        for line in f:
            clean_line = line.rstrip()
            # Skip empty lines to avoid errors when splitting
            if not clean_line:
                continue
            x_str, y_str, z_str = clean_line.split()
            # Convert to floats and yield the point
            yield (float(x_str), float(y_str), float(z_str))

Step 2: Build a Batch Generator

Now, we'll create a wrapper generator that takes points from the base generator and groups them into batches of 5. We'll use itertools.islice to grab exactly 5 elements at a time:

def gen_point_batches(file_path, batch_size=5):
    # Create an instance of our base point generator
    point_generator = gen_points(file_path)
    
    while True:
        # Grab up to `batch_size` points from the generator
        batch = list(itertools.islice(point_generator, batch_size))
        
        if not batch:
            # If the batch is empty, we've reached the end of the file
            break
        
        # Yield the batch of points
        yield batch

How to Use It

You can now iterate over batches like this—each time you call next() on the batch generator, you'll get a list of up to 5 points:

# Replace with your actual file path
file_name = r"D:\master ppt\S..."

# Iterate through batches
for batch in gen_point_batches(file_name):
    print(f"Batch of {len(batch)} points:")
    for x, y, z in batch:
        print(f"  ({x}, {y}, {z})")

Why This Works

  • itertools.islice is perfect here because it lets us pull a fixed number of elements from an iterator (your generator) without loading the entire file into memory—great for large files!
  • The while True loop keeps fetching batches until there are no more points left (when batch is empty).
  • The with statement ensures your file is properly closed, so you don't have to remember to call f.close() manually.

For your first question (returning multiple lines/data per next() call in general), this pattern applies: wrap your single-element generator with another generator that collects elements into batches using either itertools.islice or a manual counter to gather items until you hit your desired batch size.

内容的提问来源于stack exchange,提问作者ssy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:06:18