是否有更简洁的方式来限制来自发电机的物品数量?
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
答案 0 :(得分:1)
def next_dummy_item():
for i in range(1, 10):
yield i
for item in itertools.islice(next_dummy_item(), 5):
# process item