Review the list first to explain
1 lista = range (ten)2 for in Lista]
Then the LISTB will be 0 to 9 of the two-time side.
There is now such a requirement that the first 10 Fibonacci numbers need to be stored to the hard disk.
So write the function that produces the Fibonacci number first:
1 def fib (max): 2 N,a,b = 0,0,13 while n < Max:4 print(b)5 A, b= b,a +6 n+=1
This will print out the previous Max Fibonacci number. And then we'll change it a little bit. (because we need to save it to the hard drive)
1 fiblist = [] 2def fib (max): 3 n,a,b = 0,0,1 4 while n < Max: 5 fiblist.append (b) 6a b = B,a + b 7 N+=1 8 9 fib (fiblist)
The next thing you can do is save the fiblist to your hard drive.
This may be done in the top 10, the top 100 might not be a problem, but if one day the business needs to save 100,000 that would be unlucky. The length of the fiblist is 100,000, the memory is not enough. What about this, directly modifying the FIB function to write directly to the hard disk instead of appending to the list? But if one day the business logic to change what to do, do not save the hard disk, storage database. This is obviously not a good idea.
There is a keyword in python, called yield, that can solve this problem.
To modify the code:
1 def fib (max): 2 N,a,b = 0,0,13 while n < Max:4 yield B5 a b = b,a + b6 n+=178 temp = FIB (ten)9 Print(temp)
Now, the output becomes the <generator object fib at 0x0354fc10>
The 0x section behind the Ps:at may be different.
What is this thing? This is the generator in Python. That is, a traversal object.
Now that we can iterate, we can use the For statement.
1 deffib (max):2N,a,b = 0,0,13 whileN <Max:4 yieldb5A, B = B,a +b6N+=17 8 forIinchFIB (10000):9 #Do somethingTen Pass
Do what you have to do now, the memory will not burst.
In addition, the list interpretation in Python can be quickly changed to a generator:
1 for in range (10)]
This is the list explanation instead of the generator:
1 for in range (10))
The difference is just to change [] to ()
Summarize:
The generator is like the IEnumerable interface in C # (this is not accurate, it is exactly the method with GetEnumerator)
Python Learning Builder in -39.python