python base generator

. 1  Import Time
 2  # Python when we need in a loop body, similar to the following command can be used to generate a regular list, and this list is circulated. The following statement referred to a list of formula. 
3  # When the list is large scale circulation in the loop it needs to start to finish the whole cycle occupy the same total amount of memory space, but also may only need access to the entire body of the loop in front of several data, this time resulting in a waste of space. 
. 4 List1 = [I 2 ** for I in Range (10 )]
 . 5  Print (List1)
 . 6  # list of the formula '[]' to '()' is about to formula list generator, the generator only the corresponding data will be generated when you call, does not cause memory camped. 
. 7 generator1 = (I 2 ** for I in Range (10 ))
 . 8  Print (generator1)
 . 9  for I in generator1:
 10     Print (i)
 11  # contents of the list by [index] subscript get, how to generator data acquisition it? By next () method takes a a a for loop or a take, there is no other way. 
12 is Generator2 = (I 2 ** for I in Range (10 ))
 13 is  Print (Generator2. __Next__ ()) # 0 
14  Print (Generator2. __Next__ ()) # . 1 
15  
16  # when a simple cycle can not meet a list of formula when the volume data generation rules, how we use a generator function to generate it? 
17  # generated string ip address generator, only need to add the constructed string round the yield 
18 is L1 = [I for I in Range (0,256 )]
 . 19 L2 =l1.copy ()
 20 is L3 = l1.copy ()
 21 is  DEF str_ip (ip_start):
 22 is      for IP1 in Range (256 ):
 23 is          for IP2 in Range (256 ):
 24              for IP3 in Range (256 ):
 25                  ip_str_format = " % S.% S.% S.% S " % (STR (ip_start), STR (IP1), STR (IP2), STR (IP3))
 26 is                  the yield ip_str_format
 27  
28  # function call which was assigned to a variable, this variable is the generator case 
29 str_ip_gen = str_ip (66 )
30  # using generators next method to obtain data 
31 is  for I in Range (300 ):
 32      Print (str_ip_gen. __Next__ ())

 

Guess you like

Origin www.cnblogs.com/flags-blog/p/11939314.html