标签云

微信群

扫码加入我们

WeChat QR Code

This question already has an answer here:

I have two ways to loop data, one using with for loop another with yield, I want to know what's the difference.

  1. For Loop(get 100000 data)

    data='select 100000 data from database'
    
    for d in date:
        do something with d    
    
  2. yield (get 1000 data every time,then query database 100 times)

    def func():
        data='select 1000 data from database'
        while date.count>0:
            yield data
    
    data = func()   
    for d in data:
        do something with d
    


It depends on how your database implementation works.

2018年08月16日26分45秒

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.

2018年08月16日26分45秒

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

2018年08月15日26分45秒

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).

2018年08月16日26分45秒

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

2018年08月16日26分45秒

Veelian: Functionally, no. Stylistically, yes.

2018年08月15日26分45秒

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

2018年08月16日26分45秒

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.

2018年08月16日26分45秒

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

2018年08月15日26分45秒