A summary of the techniques of object iteration and iteration in Python

Source: Internet
Author: User
Tags iterable
How can I implement an iterative object and an iterator object?

Practical cases

A software requires fetching the scent information of each city from the network, and then displays:

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

If a crawl all the city weather again show, show the first city temperature, there is a high delay, and waste storage space, we expect to access the strategy in time, and all the city temperature encapsulated into an object, can be used for the iteration of the statement, how to solve?

Solution Solutions

Implements an iterator object Weatherlterator that returns a next city temperature each time, implementing an iterative object Weatherlterable ,———— The Iter__ method returns an iterator object

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) # Iterative 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)

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: Lo 27 ℃, High temp 33℃process finished with exit code 0

Second, how to use the generator function to implement an iterative object?

Practical cases

A class that implements an iterative object that iterates over all the primes in a given range:

Python pn = primenumbers (1, +) for K in Pn:print (k) ' Output results text2 3 5 7 11 13 17 19 23 29 "'

Solution Solutions

-Implement the generator function for the method of the class __iter__ , yield returning 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.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, Process finished with exit code 0

Thirdly, how to reverse iterate and how to implement reverse iteration?

Practical cases

Implement a continuous floating-point generator FloatRange (and rrange similar) to start produce some column continuous floating-point numbers based on a given range (, stop ) and step value ( step ), such as iterating FloatRange(3.0,4.0,0.2) to produce a 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 Solutions

A method for implementing a reverse iterative protocol that __reversed__ 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 T + = Self.step def __reversed__ (self): T = Self.stop while T & gt;= Self.start:yield T-= self.step print ("Positive phase Iteration-----") for N in Floatrange (1.0, 4.0, 0.5): print (n) print ("Inverse 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 Reverse 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 an iterator?

Practical cases

There is a text file, we want to go to a certain range of content, such as the content between 100~300, Python Chinese This file is an iterative object, can we use similar list slices to get a 100~300 line file content generator?

Solution Solutions

Using the standard library itertools.islice , it can return the generator of an iterator object slice

From itertools import islice f = open (' Access.log ') # # First 500 lines # islice (f, 500) # # 100 lines after # 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 Ten, three, four. Process fin Ished with exit code 0

How can I iterate over multiple iterated objects in a for statement?

Practical cases

1, a class of students final exam results, Chinese, maths, English stored in 3 more lists, while iterating over three lists, calculate each student's total score (parallel)

2, a certain age has four classes, a test did not class English scores are stored in four lists, sequentially iterating through each list, statistics for the full school year results higher than 90 people (serial)

Solution Solutions

Parallel: Using built-in functions zip , it can merge multiple iterative objects, returning one tuple per iteration

From random import Randint # shanghai Chinese results, # 40 people, score again 60-100 between Chinese = [Randint (max) for _ in range (+)] Math = [Randint (60, (+) for _ in range (40)] # Math 中文版 = [Randint (max.) 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, 225] Process finished with exit code 0

Serial: Using the standard library itertools.chain , it can connect multiple objects that can be iterated

From random import randint from itertools import chain # generates random results for four classes e1 = [Randint (+) for _ in range (+)] E2 = [Randi NT (at) E3 = [Randint (max)] e4 = [Randint (max.) for _ in range (50)] # Default (max.). Number of =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 everyone's study or work to bring some help, if there are questions you can message exchange.

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.