Can determine whether the iteration
In [4]: from collections import Iterable
In [6]: isinstance(123,Iterable)
Out[6]: False
In [11]: isinstance((123),Iterable)
Out[11]: False
In [12]: isinstance((123,),Iterable)
Out[12]: True
In [13]: isinstance([123],Iterable)
Out[13]: True
In [14]: isinstance("123",Iterable)
Out[14]: True
In [15]: isinstance({1:1,2:2},Iterable)
Out[15]: True
Iterator
nums = list() a = 0 b = 1 i = 0 while i < 10: nums.append(a) a, b = b, a + b i += 1 for num in nums: print(num)
import time from collections import Iterable from collections import Iterator class Fibonacci(object): def __init__(self, all_num): self.all_num = all_num self.current_num = 0 self.a = 0 self.b = 1 def __iter__(self): return self def __next__(self): if self.current_num < self.all_num: ret = self.a self.a, self.b = self.b, self.a + self.b self.current_num += 1 return ret else: raise StopIteration fibo = Fibonacci (10 ) for num in fibo: print(num, end=" ")
def create_num(all_num): print("---1---") A, B = 0,. 1 CURRENT_NUM = 0 the while CURRENT_NUM < all_num: Print ( " --- 2 --- " ) yield A # if so the yield statement template is not a function, but a function generated Print ( " --- 3 --- " ) a, b = b, a + b current_num += 1 print("---4---") # If you call functions and found that this function has a yield so instead of calling the function but create a generator object obj = create_num (10 ) # for NUM in obj: # Print (NUM) the Result = the Next (obj) Print ( result)
import gevent import time def f1(n): for i in range(n): print(gevent.getcurrent(), i) gevent.sleep(0.5) def f2(n): for i in range(n): print(gevent.getcurrent(), i) gevent.sleep(0.5) def f3(n): for i in range(n): print(gevent.getcurrent(), i) gevent.sleep(0.5) print("--1--") g1 = gevent.spawn(f1, 5) print("--2--") g2 = gevent.spawn(f2, 5) print("--3--") g3 = gevent.spawn(f3, 5) print("--4--") g1.join() g2.join() g3.join()
peddled demo
from gevent Import Monkey Import gevent Import Random Import Time # required when there is time-consuming operation monkey.patch_all () # code time-consuming procedures used in the operation, transposition module gevent implemented in their own def f1(n): for i in range(n): print(gevent.getcurrent(), i) time.sleep(random.random()) def f2(n): for i in range(n): print(gevent.getcurrent(), i) time.sleep(random.random()) def f3(n): for i in range(n): print(gevent.getcurrent(), i) time.sleep(random.random()) gevent.joinall ([ gevent.spawn (f1, 5 ), gevent.spawn (f 2, 5 ), gevent.spawn (f3, 5 ) ])