首页 > 解决方案 > python生成器创建从另一个生成器馈送的项目列表

问题描述

我正在尝试从输入生成器函数创建批次列表,但它不会产生我期望的列表。

def batch_generator(items, batch_size):
new = []
i = 0

for item in items: 
    new.append(item)
    i += 1
    print('new: ', new, i)
    if i == batch_size:
        print('i = batch')
        i = 0
        yield new
        new = []


def _test_items_generator():
    for i in range(10):
        yield i

print(list(map(lambda x: len(x), 
               batch_generator(_test_items_generator(), 3))))

我试图让输出为 [[0, 1, 2], [3, 4 ,5], [6, 7, 8], [9]] 产量似乎发送的是 batch_size 而不是信息在新列表中。试图让我的头脑了解这些生成器是如何工作的!

标签: pythonlistgenerator

解决方案


我认为问题出在你的最后一行:

print(list(map(lambda x: len(x), 
           batch_generator(_test_items_generator(), 3))))

batch_generatoryieldnew包含一个列表。然后您map(lambda x: len(x)返回每个列表的 len。然后打印返回的长度列表map()

这是产生您期望的输出的代码:

def batch_generator(items, batch_size):
    new = []
    i = 0

    for item in items: 
        new.append(item)
        i += 1
        print('new: ', new, i)
        if i == batch_size:
            print('i = batch')
            i = 0
            yield new
            new = []

    yield new # yield the last list even if it is smaller than batch size

def _test_items_generator():
    for i in range(10):
        yield i

print(list( batch_generator(_test_items_generator(), 3)))

推荐阅读