标签云

微信群

扫码加入我们

WeChat QR Code

This question already has an answer here:What does the “yield” keyword do?42 answersI have two ways to loop data, one using with for loopanother with yield, I want to know what's the difference.For Loop(get 100000 data)data='select 100000 data from database'for d in date:do something with dyield (get 1000 data every time,then query database 100 times)def func():data='select 1000 data from database'while date.count>0:yield datadata = func() for d in data:do something with d


It depends on how your database implementation works.

2019年05月22日30分31秒

In this case, it completely depends on what you do in func. If you generate the complete list at once, then you have no advantage of using yield over loop. If you generate it one by one, then yield will help.

2019年05月22日30分31秒

Are you asking what yield does, or are you asking if it will be more efficient to split up a large database query?

2019年05月22日30分31秒

Is date different from data? What is func() supposed to do? If date=data and the select line in supposed to represent a database read, and .count was a valid attribute describing how many results were returned, then the loop would yield the entire database read infinitely (if it was non-empty).

2019年05月22日30分31秒

Do you mean: there is no difference between the two ways? thanks

2019年05月23日30分31秒

Veelian: Functionally, no. Stylistically, yes.

2019年05月22日30分31秒

they are functionally not the same, generators are not the same as iterators.

2019年05月23日30分31秒

dnozay: That's a rather strange line of reasoning. If X is not the same Y doesn't mean that X and Y can't be used to do the same thing.

2019年05月22日30分31秒

NPE, recursion and iteration are also not the same thing, even though people use it to calculate fibonacci numbers.

2019年05月22日30分31秒