3.1. How to achieve iterables and iterator object
# 3.1 How to achieve iterables and iterator object Import Requests from collections.abc Import Iterable, Iterator class WeatherIterator (Iterator): DEF __init__ (Self, Cities): self.cities = Cities # iterations from a list city, index it +1 self.index = 0 DEF __next__ (Self): # If all cities are iterations over, throwing an exception IF self.index == len (self.cities): the raise StopIteration # current iteration city city = Self. cities [self.index] # Iteration End current city, index it + 1'd self.index + =. 1 return self.get_weather (City) DEF get_weather (Self, City): URL = ' http://wthrcdn.etouch.cn/weather_mini?city= ' + city r = requests.get (url) # get the day's weather information the Data = r.json () [ ' the Data ' ] [ ' Forecast ' ] [0] # returns the name of the city, maximum and minimum temperatures return city, the Data [ ' High ' ], Data [ ' Low ' ] class WeatherIterable(Iterable): def __init__(self,cities): self.cities = cities def __iter__(self): return WeatherIterator(self.cities) def show(w): for x in w: print(x) weather = WeatherIterable(['北京','上海','广州','深圳','东莞']) show(weather)
result
3.2 How to use the generator function implemented iterables
# 3.2 How to use the generator function implemented iterables from collections.abc Import the Iterable class PrimeNumbers (the Iterable): DEF the __init__ (Self, A, B): self.a = A self.b, = B DEF the __iter__ (Self): for K in Range (self.a, self.b,): IF self.is_prime (K): the yield K DEF is_prime (Self, K): return False IF K <2 the else All (Map ( the lambda X: X K%, Range (2, K))) # printing 1-30 direct prime PN PrimeNumbers = (. 1, 30 ) for n- in PN: Print (n-)
3.3. How to reverse iteration and how to implement reverse iteration
Reverse iteration
In [75]: l = [1,2,3,4,5] In [76]: for x in l: ...: print(x) ...: 1 2 3 4 5 In [77]: for x in reversed(l): ...: print(x) ...: 5 4 3 2 1
To achieve reverse iterator method must implement __reversed__
# 3.3 How reverse iteration and how reverse iteration. Class IntRange: DEF the __init__ (Self, A, B, STEP): self.a = A self.b, = B self.step = STEP DEF the __iter__ (Self): T = self.a the while T <= self.b,: the yield T T + = self.step DEF __reversed__ (Self): T = self.b, the while T> = self.a: the yield t t -= self.step fr = IntRange(1, 10, 2) for x in fr: print(x) print('=' * 30) #反向迭代 for y in reversed(fr): print(y)