zoukankan      html  css  js  c++  java
  • 生产器

     1 '''
     2 生成器:
     3 概念:使用yield的函数被称为是生成器函数。generator
     4 与普通函数区别:生成器函数是一个返回迭代器的函数,
     5 只能用于迭代操作。可以认为生成器就是一个迭代器。
     6 '''
     7 # 系统的生成器
     8 li1 = (x for x in range(3))   # [0,1,2]
     9 print(li1)
    10 print(type(li1))  # generator
    11 
    12 li2 = (x*2 for x in range(4))  # [0, 2, 4, 6]
    13 for i in li2:
    14     print(i)
    15 
    16 li3 = (3 for x in range(3))
    17 print(list(li3))
    18 
    19 
    20 li4 = (x for x in range(11) if x % 2 == 0)
    21 print(list(li4))
    22 
    23 l = []
    24 for i in range(11):
    25     if i % 2 == 0:
    26         l.append(i)
    27 print(l)
    28 
    29 
    30 # 函数
    31 def func1():
    32     print("--1--")
    33     print("--2--")
    34     print("--3--")
    35 func1()
    36 print(type(func1))  # function
    37 print(type(func1()))   # NoneType
    38 
    39 # 生成器函数
    40 def func2():
    41     print("***111***")
    42     print(3456789)
    43     yield
    44     print("***222***")
    45     yield
    46     print("***333***")
    47     yield
    48 print(type(func2))  # function
    49 print(type(func2()))   # generator
    50 print('----------------------------------------')
    51 a = func2()
    52 next(a)
    53 next(a)
    54 next(a)
    55 # next(a)   # StopIteration
    56 
    57 def func3():
    58     print("---111---")
    59     yield "a"
    60     print("---222---")
    61     yield "b"
    62     print("---333---")
    63     yield
    64 
    65 b = func3()
    66 print(next(b))
    67 print(next(b))
    68 print(next(b))   # None
  • 相关阅读:
    Leetcode: Palindrome Permutation
    Leetcode: Ugly Number
    Leetcode: Ugly Number II
    Leetcode: Single Number III
    Leetcode: 3Sum Smaller
    Leetcode: Factor Combinations
    Leetcode: Different Ways to Add Parentheses
    Leetcode: Add Digits
    GigE IP地址配置
    Ubuntu 关闭触摸板
  • 原文地址:https://www.cnblogs.com/BKY88888888/p/11266047.html
Copyright © 2011-2022 走看看