Geradores para os mais pequenos

Olá a todos! Quando estava estudando Python sozinho, encontrei material teórico suficiente sobre a linguagem e seus recursos. Porém, mesmo depois de ler vários artigos em diversos sites e livros, muita coisa não cabia na minha cabeça (sim, estou tão apertado). Conceitos incompreensíveis tiveram de ser amontoados "na fé", sem um entendimento profundo, porque os exemplos práticos nos artigos eram difíceis para mim. O tempo passou, ganhei mais experiência, o entendimento surgiu sobre problemas práticos e, em algum momento, comecei a ensinar Python para meus amigos. Por meio da orientação, descobri que pareço ter traçado um caminho no qual conceitos complexos podem ser explicados em termos simples.





Com respeito a toda a comunidade de TI no Dia das Crianças e na esperança de poder ajudar os iniciantes a entender a beleza e os benefícios das coisas que são difíceis e incompreensíveis à primeira vista, estou escrevendo meu artigo de estreia.





Hoje quero falar sobre geradores novamente. Então, para a batalha!





Vamos entender os conceitos e definir a tarefa

A primeira coisa a sempre ter em mente quando alguém fala com você sobre geradores Python é não confundir "compreensões" e "geradores iteradores". O primeiro é um poderoso açúcar sintático para gerar coleções em tempo real, o último é uma forma de recuperar valores sob demanda. Hoje vamos nos concentrar no segundo.





, , : « !» , - .





      .
.

: (, , ..) -. - «». ( 3 10, - 10).





: , , . . , , , .





, :





  1. . .





  2. . .





. : , - - . , (-, , ) , - . , , . . , :)





:





    ,      .
, .

, , , . , . «», , , , - . .





:





-









20 .





40 .









30 .





50 .









25 .





5 .









15 .





35 .









10 .





25 .









30 .





35 .









30 .





50 .









20 .





15 .









15 .





15 .





Python. - . 0 100 000 000.





859 724 472 , 6 . , - , . , , . . : . ?





«» . , n , - . - -. , - . , .





, , , — . : next



, .





, , . , . , , , . , .





, , next: ,





: , 100 000 000 . 2 , — 10, (5) (3). «».





, next , -. - 100 000 000 120 ( — ), 0,00009 . , , , ( — ), .





:





  • - , , - . , , .





  • - , , . , . .





Python. , - , 0 n.





, (). , - . , 4, 2 . .





def skat(n): 
    """,     0  n""" 
    #     range,   range  -.
    res = []
    cnt = 0
    while cnt < n:
        res.append(cnt)
        cnt += 1
    return res

def first_eater(eda_list): 
""" """ 
    for eda in eda_list: 
        print(f"   {eda}  : ", str(eda)) 
      
      
def second_eater(eda_list): 
""" """ 
    for eda in eda_list: 
        print(f"   {eda}  : ", str(eda) * 4) 
      
      
def third_eater(eda_list): 
""" """ 
    for eda in eda_list: 
        print(f"   {eda}  : ", str(eda) * 10)
      
      
#  
eda_list = skat(100_000_000) 
#   
golod_1 = 2 
golod_2 = 3 
golod_3 = 4 
# 
first_eater(eda_list[:golod_1])
second_eater(eda_list[golod_1:golod_2 + golod_1])
third_eater(eda_list[golod_2 + golod_1:golod_2 + golod_1 + golod_3])

# ,     :
# >>>    0  :  0
# >>>    1  :  1
# >>>    2  :  2222
# >>>    3  :  3333
# >>>    4  :  4444
# >>>    5  :  5555555555
# >>>    6  :  6666666666
# >>>    7  :  7777777777
# >>>    8  :  8888888888
      
      



, : . , , . . , , . , , , pop



, ( ), .





, , — . ? . - (return



- ) ( return



None



). , Python return



, — yield



.





, :





def my_func_1():
  print("  ")
  return 1


def my_func_2():
  print("  ")
  yield 1
      
      



( , , ):





print(my_func_1)
print(my_func_2)

# ,     :
# >>> <function my_func_1 at 0x10c399950>
# >>> <function my_func_2 at 0x10c3a4290>
      
      



, my_func_1



my_func_2



, . . , :





print(my_func_1())
print(my_func_2())

# ,     
# >>>   
# >>> 1
# >>> <generator object my_func_2 at 0x108a702d0>
      
      



« ?» — .





« !» — .





, , yield



, - (generator-object



). , - — , , . ! , -, my_func_2



.





? ! Python next



( , ?), - ( -, , ) yield



, yield



. :





print(next(my_func_2()))

# ,     :
# >>> 1
      
      



! ! «... yield



...»? , , , - , yield



! - my_func_2



yield



:





def my_func_2():
    print("  ") 
    yield 1 
    print("   ") 
    yield 2 
    print("  !")

#     :
gen_o = my_func_2() #          generator-object

print(next(gen_o))
print(",       -  !") 
print(next(gen_o))

# ,     :
# >>>   
# >>> 1
# >>> ,       -  !
# >>>    
# >>> 2
      
      



, generator-object



next



yield



. , next



. «», . , , generator-object



, . ! .





next



:





gen_o = my_func_2()
print(next(gen_o))
print(",       -  !")
print(next(gen_o))
print(next(gen_o))

# ,     :
# >>> 1
# >>> ,       -  !
# >>>    
# >>> 2
# >>>   !
# >>> Traceback (most recent call last):
# >>> File "<  >", line 13, in <module>
# >>> print(next(gen_o))
# >>> StopIteration
      
      



, «» generator-object



. , yield



, . - , , StopIteration



.





: generator-object



«» . - «» . . generator-object



, my_func_2



.





   ,    "  ?"
, " ?"

. , , . , n, . , generator-object



, -, :





def skat(n):
    """,   -,    
        0  n"""
    cnt = 0
    while cnt < n:
        yield cnt
        cnt += 1


def first_eater(golod, skat):
    """ """
    while golod > 0:
        eda = next(skat)
        print(f"   {eda}    : ", eda)
        golod -= 1


def second_eater(golod, skat):
    """ """
    eda = next(skat)
    while golod > 0:
        print(f"   {eda}    : ", str(eda) * 4)
        golod -= 1


def third_eater(golod, skat):
    """ """
    eda = next(skat)
    while golod > 0:
        print(f"   {eda}    : ", str(eda) * 10)
        golod -= 1


skat_gen_obj = skat(100_000_000)
golod_1 = 2
golod_2 = 3
golod_3 = 4

try:
    first_eater(golod_1, skat_gen_obj)
    second_eater(golod_2, skat_gen_obj)
    third_eater(golod_3, skat_gen_obj)
except StopIteration:
    print("   !")

# ,     :
# >>>    0    :  0
# >>>    1    :  1
# >>>    2    :  2222
# >>>    2    :  2222
# >>>    2    :  2222
# >>>    3    :  3333333333
# >>>    3    :  3333333333
# >>>    3    :  3333333333
# >>>    3    :  3333333333
      
      



try - except



, . , , , .





     ,
,

«» ( , ). , , , . , , , (, «» :D) — generator-object



.





        ,         -
, -

- . , .





- . .





- , , .





, :





  • ,









  • , ,





    , :





  • ,





- , !





, :





  • , ( ) , , ,





: , , ..





,    -.
, -.

, ! , , — ). - , for



, .








All Articles