ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Generator
    python/기본 2022. 4. 29. 21:59
    l = ['a', 'b', 'c']
    
    for i in l:
        print(i)
    
    
    ####################################################################
    # Generator
    
    def greeting():
        yield 'a'
        yield 'b'
        yield 'c'
    
    
    # for g in greeting():
    #    print(g)
    
    
    g = greeting()
    print(next(g))  # a
    print(next(g))  # b
    print(next(g))  # c
    # print(next(g))  # StopIteration
    
    ####################################################################
    t = (1, 2, 3, 4, 5)
    t2 = (5, 6, 7, 8, 9, 10)
    
    r = [i for i in t if i % 2 == 0]
    print(r)  # [2, 4]
    
    r = [i * j for i in t for j in t2]
    print(r)  # [5, 6, 7, 8, 9, 10, 10, 12, .. ]
    
    ####################################################################
    w = ['a', 'b', 'c']
    f = [1, 2, 3]
    
    d = {}
    for x, y in zip(w, f):
        d[x] = y
    print(d)  # {'a': 1, 'b': 2, 'c': 3}
    
    d = {x: y for x, y in zip(w, f)}
    d2 = dict(zip(w, f))
    
    ####################################################################
    s = set()
    for i in range(10):
        if i % 2 == 0:
            s.add(i)
    
    s = {i for i in range(10) if i % 2 == 0}
    print(s)  # {0, 2, 4, 6, 8}
    
    
    ####################################################################
    def g():
        for i in range(10):
            yield i
    
    
    g = g()
    print(type(g))  # <class 'generator'>
    
    g = (i for i in range(10) if i % 2 == 0)
    print(type(g))  # <class 'generator'>
    for x in g:
        print(x)  # 0 2 4 6 8
    
    g = tuple(i for i in range(10))
    print(type(g))  # <class 'tuple'>

    'python > 기본' 카테고리의 다른 글

    Exception  (0) 2022.04.29
    Namespace & Scope  (0) 2022.04.29
    Lambda  (0) 2022.04.29
    Decorator / contextmanager  (0) 2022.04.29
    Closure  (0) 2022.04.29

    댓글

Designed by Tistory.