Python iterator and generator instance details, python Generator

Source: Internet
Author: User

Python iterator and generator instance details, python Generator

Python iterator and generator instance details

1. How to Implement iteratable objects and iterator objects

1. Get the iterator object from the iteratable object

For example, l is an iteratable object, and iter (l) is an iterator object.

In [1]: l = [1, 2, 3, 4] In [2]: l. _ iter _ Out [2]: <method-wrapper '_ iter _' of list object at 0x0000000001_c7c8> In [3]: t = iter (l) in [4]: t. next () Out [4]: 1In [5]: t. next () Out [5]: 2In [6]: t. next () Out [6]: 3In [7]: t. next () Out [7]: 4In [8]: t. next () ------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-8-3660e2a3d509> in <module> () ----> 1 t. the workflow of next () StopIteration: for x in l: print xfor loop is to get a t from iter (l) and then call t continuously. nex (). When the StopIteration is captured, the iteration ends.

# The method for directly calling functions below is suitable for using the iterator if network I/O requirements are high when the data volume is large.

Def getWeather (city): r = requests. get (u'http: // wthrcdn.etouch.cn/weather_mini? City = '+ city) data = r. json () ['data'] ['forecast '] [0] return' % s: % s, % s' % (city, data ['low'], data ['high']) print getWeather (u'beijing') return value:
Beijing: Low Temperature 13 ℃, high temperature 28 ℃

Implement a WeatherIterator object. The next method returns the temperature of a city each time.

Implements a WeatherIterable object, and the iter method returns an iterator object.

#-*-Coding: UTF-8-*-import requestsfrom collections import Iterable, Iteratorclass WeatherIterator (Iterator): def _ init _ (self, cities): self. cities = cities self. index = 0 def getWeather (self, city): r = requests. get (u'http: // wthrcdn.etouch.cn/weather_mini? City = '+ city) data = r. json () ['data'] ['forecast '] [0] return' % s: % s, % s' % (city, data ['low'], data ['high']) def next (self): if self. index = len (self. cities): raise StopIteration city = self. cities [self. index] self. index + = 1 return self. getWeather (city) class WeatherIterable (Iterable): def _ init _ (self, cities): self. cities = cities def _ iter _ (self): return WeatherIterator (self. cities) for x in WeatherIterable ([u 'beijing', u 'shanghai', u 'guangzhou ', u 'shenzhen']): print x. encode ('utf-8') Output: Beijing: Low Temperature 13 ℃, high temperature 28 ℃ Shanghai: Low Temperature 14 ℃, high temperature 22 ℃ Guangzhou: Low Temperature 17 ℃, high temperature 23 ℃ Shenzhen: low temperature 18 ℃, high temperature 24 ℃

Ii. Use generator functions to implement iteratable objects

1. Implement a class that can iterate objects. It can iterate all prime numbers within a given range.

A prime number is defined as a prime number in a natural number greater than 1. a number that has no other factors besides 1 and itself is called a prime number.

A function with yield is a generator, which is different from a common function. Generating a generator looks like a function call, but does not execute any function code until it calls next () (next () is automatically called in the for loop to start execution. Although the execution process is still executed according to the function process, every execution of a yield statement is interrupted and an iteration value is returned. The next statement of yield continues to be executed during the next execution. It seems that a function is interrupted several times by yield during normal execution, and the current iteration value is returned through yield for each interruption.

Class PrimeNumbers: def _ init _ (self, start, end): self. start = start self. end = end def isPrimeNum (self, k): if k <2: return False for I in xrange (2, k): if k % I = 0: return False return True def _ iter _ (self): for k in xrange (self. start, self. end + 1): if self. isPrimeNum (k): yield kfor x in PrimeNumbers (1, 10): print x output: 2357

Iii. implement reverse Iteration

1. Reverse Iteration

For example, to implement a FloatRange (similar to xrange) floating point generator, generate a series of Continuous Floating Point Numbers Based on the given range (start, end) and step value (step), such as iterative FloatRange (3.0, 4.0, 0.2) generate a sequence:

Positive: 3.0-> 3.2-> 3.4-> 3.6-> 3.8-> 4.0

Reverse: 4.0-> 3.8-> 3.6-> 3.4-> 3.2-> 3.0

Class FloatRange: def _ init _ (self, start, end, step = 0.1): self. start = start self. end = end self. step = step def _ iter _ (self): t = self. start while round (t, 14) <= round (self. end, 14): yield t = t + self. step def _ reversed _ (self): t = self. end while round (t, 14)> = round (self. start, 14): yield t = t-self. stepfor x in reversed (FloatRange (3.0, 4.0, 0.2): print x output: 4.03.83.63.43.23.0for x in FloatRange (3.0, 4.0, 0.2 ):
Print x
Output:
3.0
3.2
3.4
3.6
3.8
4.0

The above Code uses the round function because the floating point numbers have precision problems, so we need to rounding them

2. Slice the iterator

For example, if you want to read a text file in a certain range, such as the content between and lines, the text file in python is an iteratable object, can I use a list slicing method to obtain a-row file content generator?

Itertools. islice in the standard library can be used to return a generator for iterative object slicing.

F = open ('/var/log/dmesg') from itertools import islice # Slice the file content between 100 and 300 rows. A generator object is returned, the default diameter is 1 islice (f, 100,300) # The first 500 lines of content islice (f, 500) #100 The End Content islice (f, 100, None) ps: every time you use islice, you need to apply for an object again, which consumes the original iteration object.

4. iterate multiple objects

1. iterate multiple iteratable objects in a for statement

1. The scores of a certain class of students are stored in three lists: Chinese, mathematics, and English. The scores are iterated to calculate the total scores of the three students (in parallel)

2. For four classes in a certain grade, the English scores of each class are stored in four lists respectively for a certain test, and each list is iterated in order to count the number of students with English scores higher than 90 in the entire school year (Serial)

Solution:

Parallel: the built-in function zip can be used to merge multiple iteratable objects and return a single tuple for each iteration.

From random import randintchinese = [randint (60,100) for _ in xrange (40)] math = [randint (60,100) for _ in xrange (40)] english = [randint (60,100) for _ in xrange (40)] total = [] for c, m, e in zip (chinese, math, english): total. append (c + m + e) print total output: [204,227,238,201,227,205,251,274,210,242,220,239,237,207,230,267,263,240,247,249,255,268,209,270,259,251,245,262,234,221,236,250,251,249,242,255,232,272,237,253]

Serial: Use itertools. chain in the standard library to connect multiple iteratable objects

From random import randintfrom itertools import chainclass1 = [randint (60,100) for _ in xrange (40)] class2 = [randint (60,100) for _ in xrange (42)] class3 = [randint (60,100) for _ in xrange (39)] class4 = [randint (60,100) for _ in xrange (43)] count = 0for s in chain (class1, class2, class3, class4): if s> 90: count = count + 1 print count output: 38

Thank you for reading this article. I hope it will help you. Thank you for your support for this site!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.