Summary of object iteration and reverse iteration techniques in Python

Source: Internet
Author: User
This article will share with you the object iteration and anti-iteration skills in Python through examples, which will be of reference value for you to learn or use python. If necessary, let's take a look. 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,nextThe 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 timeyieldReturns 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(AndrrangeSimilarly), 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.isliceIt 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 functionszipIt 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.chainIt 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.

For more information about object iteration and reverse iteration in Python, see PHP!

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.