How do I implement an iterative object and an iterator object?
Actual case
A software requirement to crawl the scent of each city from the network, and then show:
Beijing: 15 ~ 20 Tianjin: 17 ~ 22 Changchun: 12 ~ 18 ...
If you crawl all the city weather again, show the first city temperature, there is a high latency, and waste of storage space, we expect to use the strategy of access, and all the city temperature package into an object, can be used for the iteration, how to solve?
Solution
Implements an iterator object that returns an iterator object Weatherlterator
next
each time a city temperature is returned and an iterative object is implemented Weatherlterable
,———— iter__ method
Import requests from collections import iterable, iterator # Temperature iterator class Weatheriterator (iterator): Def __init__ (self, CIT IES): self.cities = Cities Self.index = 0 def getWeather (self, city): R = Requests.get (' http://wthrcdn.etouch.cn/weather_m Ini?city= ' + City "data = R.json () [' Data '] [' forecast '][0] return '%s:%s,%s '% (city, data[' low '], data[' High '] def __ne Xt__ (self): if Self.index = = Len (self.cities): Raise stopiteration city = Self.cities[self.index] Self.index + 1 return s Elf.getweather (city) # Iteration object class Weatheriterable (iterable): Def __init__ (self, cities): self.cities = Cities def __iter_ _ (Self): return Weatheriterator (Self.cities) to X in weatheriterable ([' Beijing ', ' Shanghai ', ' Guangzhou ', ' Shenzhen ']): print (x)
The results of the implementation are as follows:
C:\Python\Python35\python.exe e:/python-intensive-training/s2.py Beijing: Low temperature 21 ℃, high temperature 30℃ Shanghai: Low temperature 23 ℃, high temperature 26℃ guangzhou: Low temperature 26 ℃, high temperature 34 ℃ Shenzhen: Low temperature 27 ℃, high temperature 33℃process finished with exit code 0
How do I use a builder function to implement an iterative object?
Actual case
A class that implements an iterative object that can iterate through all the primes in a given range:
Python pn = primenumbers (1) for K in Pn:print (k) ' Output result text
2 3 5 7 '
Solution
-Implements the method of the class to the __iter__
generator function, yield
returning a prime number at a time
Class Primenumbers:def __init__ (self, start, stop): Self.start = Start Self.stop = Stop def isprimenum (self, k): if K ; 2:return false for I in range (2, K): if k% i = = 0:return False return True def __iter__ (self): for K in range (Self.star T, Self.stop + 1): If Self.isprimenum (k): Yield K for x in Primenumbers (1): Print (x)
Run results
C:\Python\Python35\python.exe e:/python-intensive-training/s3.py 2 3 5 7 km Process finished with exit code 0
How to do reverse iteration and how to implement reverse iteration?
Actual case
Implements a continuous floating-point FloatRange
number generator (and rrange
similar) that start
stop
step
produces some column-continuous floating-point numbers, such as iterations, based on a given range (,), and a stepping value (), such as an iterative generation FloatRange(3.0,4.0,0.2)
sequence:
Forward: 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
Solution
A method for implementing a reverse iterative protocol __reversed__
that returns a reverse iterator
Class Floatrange:def __init__ (self, start, stop, step=0.1): Self.start = Start Self.stop = Stop Self.step = Step def __it Er__ (self): T = Self.start while t <= self.stop:yield t = + self.step def __reversed__ (self): T = Self.stop while T & gt;= Self.start:yield T-= self.step print ("Forward Iteration-----") for N in Floatrange (1.0, 4.0, 0.5): print (n) print ("Anti-Iteration-----") For x in Reversed (Floatrange (1.0, 4.0, 0.5)): Print (x)
Output results
C:\Python\Python35\python.exe e:/python-intensive-training/s4.py Positive Phase Iteration-----1.0 1.5 2.0 2.5 3.0 3.5 4.0 Back Iteration-----4.0 3.5 3. 0 2.5 2.0 1.5 1.0 Process finished with exit code 0
Iv. How do I slice the iterator?
Actual case
There is a text file, we want to go to a range of content, such as 100~300 between the content, Python Chinese this file is an iterative object, we can use like a list of slices to get a 100~300 of the contents of the row file generator?
Solution
Using the standard library itertools.islice
, it can return a builder for an iterator object slice
From itertools import islice f = open (' Access.log ') # Top 500 lines # islice (f, 500) # 100 # islice (f, None) for line In Islice (f,100,300): Print (line)
Islice Each lecture consumes the previous iteration object
L = Range T = ITER (L) for x in Islice (T, 5): print (x) print (' second iteration ') for x in T:print (x)
Output results
C:\Python\Python35\python.exe e:/python-intensive-training/s5.py 5 6 7 8 9 second iteration of the Process fin (ii) Ished with exit code 0
How can I iterate over multiple iteration objects in a for statement?
Actual case
1, a class of students final exam results, Chinese, maths, English, respectively, store 3 lists, and iterate three lists, calculate each student's total score (parallel)
2, a certain age has four classes, a Test no class of English results are stored in four lists, and then iterate each list, the total academic year scores above 90 points (serial)
Solution
Parallel: Using built-in functions zip
, it can combine multiple iterations and return a tuple each iteration
From random import Randint # Shanghai language results, # 40 people, scores and 60-100 between Chinese = [Randint (m) for _ in range ()] Math = [Randint (60, For _ in range (40)] # Math 中文版 = [Randint for _ in range (40)] # english total = [] for C, M, E in Zip (Chinese, Math, 中文版): Total.append (c + M + E) print (total)
The results of the implementation are as follows:
C:\Python\Python35\python.exe e:/python-intensive-training/s6.py [232, 234, 259, 248, 241, 236, 245, 253, 275, 238, 240, 2 39, 283, 256, 232, 224, 201, 255, 206, 239, 254, 216, 287, 268, 235, 223, 289, 221, 266, 222, 231, 240, 226, 235, 255, 232 , 235, 241, the finished with exit code 0
Serial: Using the standard library itertools.chain
, it can connect multiple iterated objects
From random import randint from itertools import chain # generates four classes of random scores e1 = [Randint (a) for _ in range ()] e2 = [Randi NT (MB) for _ in range ()] E3 = [Randint to _ in range ()] e4 = [Randint (m) for _ in range (50)] # Default Number =1 count = 0 for S in Chain (E1, E2, E3, E4): # If the current score is greater than 90, let count+1 if s > 90:count + + 1 print (count)
Output results
C:\Python\Python35\python.exe e:/python-intensive-training/s6.py Process finished with exit code 0
Summarize
The above is the entire content of this article, I hope that the study or work to bring some help, if you have questions you can message exchange.