Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement the Generator in Python

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to implement generators in Python". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn "how to implement the generator in Python"!

preface

Generators are easy to implement, but not easy to understand. Generators can also be used to create iterators, but generators can be used to return elements of an iterable collection one at a time. Now let's look at an example:

def yrange(n): i = 0 while i

< n: yield i i += 1 每次执行 yield 语句时,函数都会生成一个新值。 "生成器"这个词被混淆地用来表示生成的函数和它生成的内容。 当调用生成器函数时,它甚至没有开始执行该函数就返回一个生成器对象。 当第一次调用 next() 方法时,函数开始执行直到它到达 yield 语句。 产生的值由下一次调用返回。 以下示例演示了 yield 和对生成器对象上的 next 方法的调用之间的相互作用。 >

>> def foo():... print("begin")... for i in range(3):... print("before yield", i)... yield i... print("after yield", i)... print("end")...>>> f = foo()>>> next(f)beginbefore yield 00>>> next(f)after yield 0before yield 11>>> next(f)after yield 1before yield 22>>> next(f)after yield 2endTraceback (most recent call last): File "", line 1, in next(f)StopIteration>>> Generators are also iterators

Generators are also iterators and support the use of for loops. The generator runs when you start iterating through a set of items with a for statement. Once the generator's function code reaches the yield statement, the generator returns its execution to the for loop, returning a new value from the collection. The generator function can generate as many values as needed (possibly infinite), generating each value in turn.

f_2 = foo()for i in f_2: print(i)beginbefore yield 00after yield 0endbefore yield 11after yield 1endbefore yield 22after yield 2end

When a function contains yield, Python automatically implements an iterator that applies all the methods we need, such as__iter__() and__next__(), so generators can also have the same functionality as iterators, as follows:

def yrange(): i = 1 while True: yield i i = i + 1def squares(): for i in yrange(): yield i * idef take(n, seq): seq = iter(seq) result = [] try: for i in range(n): result.append(next(seq)) except StopIteration: pass return resultprint(take(5, squares()))# [1, 4, 9, 16, 25]

Next, let's look at how to calculate Fibonacci sequences using the generator:

def fib(n): if n 0: return False elif n == 2 or n == 3: return True for x in range(2, int(n**0.5) + 1): if n % x == 0: return False return Truedef getPrimes(): value = 0 while True: if isPrime(value): i = yield value if i is not None: value = i value += 1

Then we call the send() function, which passes a value to the generator prime_gen and calculates the value of the next prime from that value:

prime_gen = getPrimes()print(next(prime_gen))print(prime_gen.send(1000))print(next(prime_gen))

You can see the following results:

throw() allows you to throw exceptions using generators. For example, this is useful for ending iterations with a certain value. For example, if we want to find prime numbers less than 20, we can use the following method:

prime_gen = getPrimes()for x in prime_gen: if x > 20: prime_gen.throw(ValueError, "I think it was enough! ") print(x)

Running this code gives the following result:

In the previous example, we stopped iterating by throwing an exception, but that's not what the user wants to see. Who wants to see an error reported? Therefore, a better way to end the iteration is to use close():

prime_gen = getPrimes()for x in prime_gen: if x > 20: prime_gen.close() print(x)

The operation result is as follows:

As you can see, the generator stopped running without throwing any exceptions.

At this point, I believe that everyone has a deeper understanding of "how to implement generators in Python," so let's actually operate them! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report