【问题标题】:restrict number of items obtained from python generator [duplicate]限制从python生成器获得的项目数量[重复]
【发布时间】:2014-07-28 13:51:01
【问题描述】:

有没有比跟随更简洁的方法来限制生成器的项目数量?

def next_dummy_item():
    for i in range(1, 10):
        yield i

item_count = 0
for item in next_dummy_item(): # can't use slicing here :(
  item_count += 1             
  # process item
  if item_count > 5:
    break

【问题讨论】:

  • @200 好的,谢谢,但我无法搜索。 :(

标签: python python-2.7 generator


【解决方案1】:

使用itertools.islice:

def next_dummy_item():
    for i in range(1, 10):
        yield i

for item in itertools.islice(next_dummy_item(), 5):
    # process item

【讨论】:

    猜你喜欢
    • 2013-04-17
    • 2018-09-12
    • 2014-01-06
    • 1970-01-01
    • 2011-03-09
    • 1970-01-01
    • 2018-09-14
    • 2013-06-28
    • 1970-01-01
    相关资源
    最近更新 更多