限制从python生成器获得的项目数

时间:2014-06-07 10:33:58

标签: python python-2.7 generator

是否有更简洁的方式来限制来自发电机的物品数量?

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

1 个答案:

答案 0 :(得分: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