Format comparison:
List imprehensions Format: [Statement for ...]
Generator format: (Statement for.. In.. )
The difference: The list stores the specific content, each element occupies space, when the need to store n data, occupy a large space
The generator store is an expression that calculates the next element by calculation and therefore occupies less space.
One, 2 kinds of input methods
#!/usr/bin/python
#Generator.next () output: A very painful way
g = (x for x in range (0, 10))
Print "G:"
Print "1g.next ():", G.next ();
Print "2g.next ():", G.next ();
Print "3g.next ():", G.next ();
Print "4g.next ():", G.next ();
Print "5g.next ():", G.next ();
Print "6g.next ():", G.next ();
Print "7g.next ():", G.next ();
Print "8g.next ():", G.next ();
Print "9g.next ():", G.next ();
Print "10g.next ():", G.next ();
#print "11g.next ():", G.next (); ---> Over range, prompt stopiteration
It is visible that the generator continues to execute from the break.
#for循环输出
K = (x for x in range (0, 10))
For X in K:
Print X
Fibonacci sequence: List vs. generator
# #Fibonacci: 1 2 3 5 8 13 21..
# #in List
def fib (n):
I, a, b = 0, 0, 1;
Print "in list:"
While I < n:
Print B;
A, B = B, a+b
i + = 1;
Print fib (6);
# #in Generator-----> Yield:generator logo
def Fibo (n):
I, a, b = 0, 0, 1;
Print "in generator:"
While I < n:
Yield B;
A, B = B, a+b
i + = 1;
For N in Fibo (6):
print n;
Python Advanced Features: Generator (generator)