【问题标题】:python generator creating list of items fed from another genertatorpython生成器创建从另一个生成器馈送的项目列表
【发布时间】:2018-11-16 07:33:56
【问题描述】:

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

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 而不是新列表中的信息。试图让我的头脑了解这些生成器是如何工作的!

【问题讨论】:

  • 你能修正你的代码缩进吗?
  • 据我所知,您只需要在batch_generator函数的底部添加if new: yield new即可。

标签: python list generator


【解决方案1】:

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

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

batch_generator 产生 new 包含一个列表。您的 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)))

【讨论】:

    【解决方案2】:

    您的生成器工作正常。但是在您的测试中,您将结果列表映射到它们的大小lambda x: len(x)

    【讨论】:

      【解决方案3】:

      batch_generator 函数的另一种方法:

      def batch_generator(items, batch_size):
          current_batch = []
      
          for i, item in enumerate(items):
            current_batch.append(item)
      
            if len(current_batch) == batch_size:
              yield current_batch
              current_batch = []
      
          if len(current_batch) < batch_size:
            yield current_batch
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-11
        • 1970-01-01
        • 2023-03-09
        • 2015-01-16
        • 2019-01-07
        • 1970-01-01
        • 2018-12-11
        相关资源
        最近更新 更多