“产量项目”的优点是什么? vs return iter(items)? [英] What are the advantages of "yield item" vs return iter(items)?
问题描述
在下面的示例中,resp.results是一个迭代器。
In the examples below, resp.results is an iterator.
版本1:
items = []
for result in resp.results:
item = process(result)
items.append(item)
return iter(items)
版本2:
for result in resp.results:
yield process(result)
返回版本1中的iter(项目)在性能/内存节省方面是否比简单地返回项目更好/更差?
Is returning iter(items) in Version 1 any better/worse in terms of performance/memory savings than simply returning items?
在Python Cookbook中,Alex说显式iter()更灵活,但不经常使用,但返回iter的优点/缺点是什么(项目)vs版本2中的收益?
In the "Python Cookbook," Alex says the explicit iter() is "more flexible but less often used," but what are the pros/cons of returning iter(items) vs yield as in Version 2?
此外,对迭代器和/或收益率进行单元测试的最佳方法是什么? - 你不能做len(结果)检查列表的大小?
Also, what are the best ways to unittest an iterator and/or yield? -- you can't do len(results) to check the size of the list?
推荐答案
很容易转动迭代器或者生成器如果需要可以返回列表:
It's easy to turn an iterator or generator back into a list if you need it:
results = [item for item in iterator]
或者在评论中明确指出,这是一种更简单的方法:
Or as kindly pointed out in the comments, an even simpler method:
results = list(iterator)
这篇关于“产量项目”的优点是什么? vs return iter(items)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!