ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 파이썬 정규표현식/ ZIP, SET함수 , YIELD제너레이터
    파이썬 2017. 11. 26. 13:22

    >>> nums = [1,2,3,4,5,6,7]

    >>> 

    >>> my_list=[n for n in nums]


           #my_list = []

           #for n in nums:

                  my_list.append(n)


    >>> print(my_list)

    [1, 2, 3, 4, 5, 6, 7]





    >>> nums = [1,2,3,4,5,6,7]


    >>> my_list = [n*n for n in nums]


           #my_list = []

           #for n in nums:

                    my_list.append(n*n)


    >>> print(my_list)

    [1, 4, 9, 16, 25, 36, 49]





    >>> nums = [1,2,3,4,5,6,7,9,10]


    >>> #my_list = []

    >>> #for n in nums:

         if n % 2 == 0:

    my_list.append(n)


    >>> #print(my_list)


    nums = [1,2,3,4,5,6,7,9,10]

    >>> my_list=[n for n in nums if n%2 == 0]

    >>> print(my_list)

    [2, 4, 6, 10]






    >>> #my_list=[]

    >>> #for letter in 'abcd':

       for num in range(4):

    my_list.append((letter,num))


    my_list=[(letter, num) for letter in 'abcd' for num in range(4)]

    >>> print(my_list)

    [('a', 0), ('a', 1), ('a', 2), ('a', 3), ('b', 0), ('b', 1), ('b', 2), ('b', 3), ('c', 0), ('c', 1), ('c', 2), ('c', 3), ('d', 0), ('d', 1), ('d', 2), ('d', 3)]





    -ZIP 함수는 2개의 리스트를 1개의 딕셔너리로 짝짓고 싶을때 사용한다.


    >>> names = ['bruce', 'clark', 'peter', 'logan', 'wade']

    >>> heros = ['batman', 'superman', 'spiderman', 'wolverine', 'deadpool']


    >>>#my_dict = {}

    >>>#for name, hero in zip(names, heros):

            my_dict[name] = hero

          #print(my_dict)


    my_dict = { name:hero for name, hero in zip(names, heros)}

    >>> print(my_dict)

    {'bruce': 'batman', 'clark': 'superman', 'peter': 'spiderman', 'logan': 'wolverine', 'wade': 'deadpool'}






    -정규표현식은 읽기 쉬울뿐 아니라 아래 빨간색처럼 함수를 추가하기도 쉽다.



    >>> my_dict = { name:hero for name, hero in zip(names, heros) if name != 'peter'}

    >>> print(my_dict)

    {'bruce': 'batman', 'clark': 'superman', 'logan': 'wolverine', 'wade': 'deadpool'}





    -SET 함수는 리스트에서 중복되는 값을 제외하고 고유값만 뽑아낸다. 


    nums = [1,1,2,1,3,4,3,4,5,5,6,7,8,9,9]

    >>> #my_set = set()

    >>> #for n in nums:

      my_set.add(n)


    >>> #print(my_set)

    {1, 2, 3, 4, 5, 6, 7, 8, 9}



    nums = [1,1,2,1,3,4,3,4,5,5,6,7,8,9,9]

    >>> my_set = {n for n in nums}

    >>> print(my_set)

    {1, 2, 3, 4, 5, 6, 7, 8, 9}





    -제너레이터, yield


    >>> nums = [1,2,3,4,5,6,7,8,9,10]

    >>> #def gen_func(nums):

        for n in nums:

    yield n*n


    >>> #my_gen = gen_func(nums)

    >>> #for i in my_gen:

           #print(i)



    >>> nums = [1,2,3,4,5,6,7,8,9,10]

    >>> my_gen = (n*n for n in nums)

    >>> 

    >>> for i in my_gen:

    print(i)


    1

    4

    9

    16

    25

    36

    49

    64

    81

    100