Summary of object iteration and anti-iteration techniques in Python, python object
1. How to Implement the iteratable objects and iterator objects?
Actual Case
A software requires that the smell information of each city be captured from the network, and the following information is displayed:
Beijing: 15 ~ 20 Tianjin: 17 ~ 22. Changchun: 12 ~ 18 ......
If the weather in all cities is captured at a time and the display shows that the temperature in the first city has a high latency and a waste of storage space, we hope to access the data in time, in addition, the temperature of all cities is encapsulated into one object, and the for statement can be used for iteration. How can this problem be solved?
Solution
Implement an iterator objectWeatherlterator
,next
The method returns the temperature of a city each time to implement an iteratable object.Weatherlterable
, ---- Iter _ method returns an iterator object
Import requests from collections import Iterable, Iterator # Temperature Iterator class WeatherIterator (Iterator): def _ init _ (self, cities): self. cities = cities self. index = 0 def getWeather (self, city): r = requests. get ('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) # iteratable object class WeatherIterable (Iterable): def _ init _ (self, cities): self. cities = cities def _ iter _ (self): return WeatherIterator (self. cities) for x in WeatherIterable (['beijing', 'shanghai', 'shanghai', 'shenzhen']): print (x)
The execution result is 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 deg C, high temperature 34 deg C Shenzhen: low temperature 27 deg C, high temperature 33 deg C Process finished with exit code 0
2. How to Use generator functions to implement iteratable objects?
Actual Case
Implement a class that can iterate objects, and it can iterate all prime numbers within a given range:
Python pn = PrimeNumbers (1, 30) for k in pn: print (k) ''output result text2 3 5 7 11 13 17 19 23 29''
Solution
-Change__iter__
Method implementation generator function, each timeyield
Returns a prime number.
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.start, self.stop + 1): if self.isPrimeNum(k): yield k for x in PrimeNumbers(1, 20): print(x)
Running result
C:\Python\Python35\python.exe E:/python-intensive-training/s3.py 2 3 5 7 11 13 17 19 Process finished with exit code 0
3. How to perform reverse iteration and how to implement reverse iteration?
Actual Case
Implement a continuous floating point generatorFloatRange
(Andrrange
Similarly), according to the given range (start
,stop
) And step value (step
) Generate continuous floating point numbers of some columns, such as iterations.FloatRange(3.0,4.0,0.2)
Generate sequence:
Forward: 3.0> 3.2> 3.4> 3.6> 3.8 reverse: 4.0> 4.0> 3.8> 3.6> 3.4> 3.2
Solution
Implement reverse iteration Protocol__reversed__
Method, it returns a reverse iterator
Class FloatRange: def _ init _ (self, start, stop, step = 0.1): self. start = start self. stop = stop self. step = step def _ iter _ (self): t = self. start while t <= self. stop: yield t + = self. step def _ reversed _ (self): t = self. stop while t> = self. start: yield t-= self. step print ("positive phase iteration -----") for n in FloatRange (1.0, 4.0, 0.5): print (n) print ("reverse iteration -----") for x in reversed (FloatRange (1.0, 4.0, 0.5): print (x)
Output result
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 anti-iteration ----- 4.0 3.5 3.0 2.5 2.0 1.5 Process finished with exit code 0
4. How to slice the iterator?
Actual Case
There is a text file, and we want to go to a specific range of content, such as 100 ~ The content between 300 rows. Text Files in python are iteratable objects. Can we use a list slicing method to get a 100 ~ Is there a 300-line file content generator?
Solution
Useitertools.islice
It can return the generator of an iterator object slicing.
From itertools import islice f = open ('access. log') # first 500 rows # islice (f, 500) # islice (f, 100, None) for line in islice (f, 100 ): print (line)
Islice consumes the previous iteration object each time it calls
L = range (20) t = iter (l) for x in islice (t, 5, 10): print (x) print ('second iteration ') for x in t: print (x)
Output result
C: \ Python \ Python35 \ python.exe E: /python-intensive-training/s5.py 5 6 7 8 9 second iteration 10 11 12 13 14 15 16 17 18 19 Process finished with exit code 0
5. How to iterate multiple iteratable objects in a for statement?
Actual Case
1. The final exam scores of a student in a class are stored in the three lists of Chinese, mathematics, and English respectively, and three lists are iterated at the same time to calculate the total score (parallel) of each student)
2. There are four classes at a certain age, and the English scores of no class in a certain test are stored in four lists respectively. Each list is iterated in order to count the number of students with scores higher than 90 in the entire school year (Serial)
Solution
Parallelism: Using built-in functionszip
It can merge multiple iteratable objects and return a single tuple for each iteration.
From random import randint # shencheng chinese score, #40 people, score between 60-60,100 chinese = [randint (60,100) for _ in range (40)] math = [randint) for _ in range (40)] # mathematical english = [randint (60,100) for _ in range (40)] # english total = [] for c, m, e in zip (chinese, math, english): total. append (c + m + e) print (total)
The execution result is as follows:
C:\Python\Python35\python.exe E:/python-intensive-training/s6.py [232, 234, 259, 248, 241, 236, 245, 253, 275, 238, 240, 239, 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, 250, 241, 225] Process finished with exit code 0
Serial: Useitertools.chain
It can connect multiple iteratable objects
From random import randint from itertools import chain # generate random scores for four classes e1 = [randint (60,100) for _ in range (40)] e2 = [randint (60,100) for _ in range (42)] e3 = [randint (60,100) for _ in range (45)] e4 = [randint (60,100) for _ in range (50)] # default count = 1 count = 0 for s in chain (e1, e2, e3, e4): # if the current score is greater than 90, set count + 1 if s> 90: count + = 1 print (count)
Output result
C:\Python\Python35\python.exe E:/python-intensive-training/s6.py 48 Process finished with exit code 0
Summary
The above is all about this article. I hope to help you in your study or work. If you have any questions, please leave a message.