English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Summary of techniques for object iteration and reverse iteration in Python

1. How to implement iterable and iterator objects?

How to iterate over multiple iterable objects in a single for statement?

A software requires fetching weather information of various cities from the network and then displaying:

Beijing: 15 ~ 20 Tianjin: 17 ~ 22 Changchun: 12 ~ 18 ......

If we fetch the weather of all cities at once and display it, there will be a significant delay in displaying the temperature of the first city, and it will waste storage space. We expect a time-based access strategy and encapsulate all city temperatures into an object, which can be iterated using a for statement. How to solve this?

Solution

Implement an iterator object WeatherIterator, the next method returns the temperature of a city each time, implement an iterable object Weatherlterable, the 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) # An iterable object class WeatherIterable(Iterable): def __init__(self, cities): self.cities = cities def __iter__(self): return WeatherIterator(self.cities) for x in WeatherIterable(['Beijing', 'Shanghai', 'Guangzhou', 'Shenzhen']): print(x)

Execution result 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

Two, how to use generator functions to implement iterable objects?

How to iterate over multiple iterable objects in a single for statement?

Implement a class that can iterate over all prime numbers within a given range:

python pn = PrimeNumbers(1, 30) for k in pn: print(k) `` Output result text
2 3 5 7 11 13 17 19 23 29
“`

Solution

-Implement the __iter__ method of the class as a generator function, which yields a prime number each 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.start, self.stop + 1): if self.isPrimeNum(k): yield k for x in PrimeNumbers(1, 20): print(x)

Running results

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

Three, how to perform reverse iteration and how to implement reverse iteration?

How to iterate over multiple iterable objects in a single for statement?

Implement a continuous floating-point number generator FloatRange (similar to rrange), which generates a series of continuous floating-point numbers based on the given range (start, stop) and step value (step), such as iterating over FloatRange(3.0,4.0,0.2) can generate a sequence:

Forward:3.0 > 3.02 > 3.04 > 3.06 > 3.08 > 4.0 Reverse:4.0 > 3.08 > 3.06 > 3.04 > 3.02 > 3.0

Solution

The __reversed__ method that implements the reverse iteration protocol, which 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 t += self.step def __reversed__(self): t = self.stop while t >= self.start: yield t t -= self.step print("Forward 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 Forward iteration----- 1.0 1.05 2.0 2.05 3.0 3.05 4.0 Reverse iteration----- 4.0 3.05 3.0 2.05 2.0 1.05 1.

.0 Process finished with exit code 0

How to iterate over multiple iterable objects in a single for statement?

How to perform slicing operations on iterators?1000 lines between content, Python text files are iterable objects, can we use a method similar to list slicing to get a3There is a certain text file, we want to get the content within a certain range of it, such as1000 lines between content, Python text files are iterable objects, can we use a method similar to list slicing to get a30~

Solution

00 lines of file content generator?

Using the standard library's itertools.islice, it can return a generator of a sliced iterator object5from itertools import islice f = open('access.log') # # The first 500 lines # islice(f, 1000) # # 100 lines after # islice(f,10) 0,30, None) for line in islice(f,

00): print(line)

islice each time will consume the previous iterable object2l = range( 5, 100) t = iter(l) for x in islice(t,

Output Result

C:\Python\Python35\python.exe E:/python-intensive-training/s5.py 5 6 7 8 9 : print(x) print('Second iteration') for x in t: print(x) 10 11 12 13 14 15 16 17 18 19 Process finished with exit code 0

Second iteration

How to iterate over multiple iterable objects in a single for statement?

1Actual case3In a certain class, the final exam scores of students in Chinese, mathematics, and English are stored in

2In a certain grade, there are four classes, and the English scores of each class in a certain exam are stored in four lists. Iterate through each list sequentially, and count the scores of the whole year that are higher than90 people with 0 points (sequential)

Solution

Parallel: Using the built-in function zip, it can merge multiple iterable objects, returning a tuple each iteration

from random import randint # Shanghai Chinese score, # 4) 0 people, the score is60-10) 0 between chinese = [randint(6) 0, 10) for _ in range(4) 0)] math = [randint(6) 0, 10) for _ in range(4) 0)] # Math english = [randint(6) 0, 10) for _ in range(4) 0)] # English total = [] for c, m, e in zip(chinese, math, english): total.append(c + m + e) print(total)

Execution result as follows:

C:\Python\Python35\python.exe E:/python-intensive-training/s6.py [232, 234, 259, 248, 241, 236, 245, 253, 275, 238, 24) 0, 239, 283, 256, 232, 224, 201, 255, 206, 239, 254, 216, 287, 268, 235, 223, 289, 221, 266, 222, 231, 24) 0, 226, 235, 255, 232, 235, 25) 0, 241, 225] Process finished with exit code 0

Sequential: Using the standard library function itertools.chain, it can connect multiple iterable objects

from random import randint from itertools import chain # Generate random scores for four classes e1 = [randint(6) 0, 10) for _ in range(4) e2 = [randint(6) 0, 10) for _ in range(42) e3 = [randint(6) 0, 10) for _ in range(45) e4 = [randint(6) 0, 10) for _ in range(5) # Default number of people=1 count = 0 for s in chain(e1, e2, e3, e4) # If the current score is greater than90, let 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

That's all for this article, I hope it can bring some help to your learning or work. If you have any questions, you can leave a message for communication.

You May Also Like