且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python:从循环中返回值而不会中断

更新时间:2022-06-24 22:36:58

print(...)替换为yield ....那么您将拥有一个生成器,它将为您提供迭代.然后,可以通过遍历结果将其转换为其他适当的数据结构.例如,要从生成器构建列表,您可以执行以下操作:

replace print(...) with yield .... then you'll have a generator which will give you an iterable. You can then turn that into some other appropriate data-structure by iterating over the result. For example, to construct a list from the generator, you could do:

list(individual(nest))  #this is prefered

在这种情况下,迭代是隐式的...

Where the iteration is implicit in this case ...

或(在这种情况下更全面,但可能提供更多信息):

or (the more round-about but possibly more informative in this context):

[ x for x in individual(nest) ]  #This is just for demonstration.