For / while the loop from python is a generator

In an interview, the interviewer asked me that some of the generators are used in Python. I know that a generator is like a function that yieldinstead return.

therefore, any of them says for/ whileloop is an example of a generator.

+4
source share
4 answers

Short answer: No , but there are other forms of generators.

A / loop - loop structure : it does not emit values ​​and, therefore, is not a generator. forwhile

However, there are other ways to build generators .

yield - , , :

def some_generator(xs):
    for x in xs:
        if x:
            yield x

, :

(x for x in xs if x)

, range(..), map(..), filter(..) .

, , ( ):

class some_generator(object):
    def __init__(self, xs):
        self.n = n
        self.idx = 0

    def __iter__(self):
        return self

    def __next__(self):
        return self.next()

    def next(self):
        while self.num < len(self.xs) and not self.xs[self.num]:
            self.num += 1
        if self.num < len(self.xs):
            res = self.xs[self.num]
            self.num += 1
            return res
        else:
            raise StopIteration()
+4

while, for . , . , for while , , for while . for while.

+5

python :

, , .. , for.

, , , .

wiki for

Python , .

, , , , , for .

+1

for and while are loop structures, and you can use them to iterate over the generators. You can take certain elements of the generator by moving it to a list.

0
source

Source: https://habr.com/ru/post/1679119/


All Articles