TIL[57]. Python_lambda

jake.log·2020년 8월 24일
0

Python

목록 보기
39/39

39.lambda

1.람다란?

  • 람다: 인라인 함수를 정의할 때 사용

  • 익명 함수(anonymous functions) 또는 람다 표현식(lambda expression)

  • 람다와 함수의 차이점

    1. 이름의 유무
    2. 람다 표현식의 본체에는 인라인 형식의 간단한 표현식만 올 수 있고 함수와 같이 return 문이 없이도 표현식의 결과가 리턴 된다.
  • 람다의 일반적인 형식(nested 될수 있고 다소 복잡한 구조를 가지기도 한다.)

    lambda argument1, argument2, ... argumentN : expression using arguments
  • 람다의 실제 예제

f = lambda x,y,z : x+y+z

print(f) # <function <lambda> at 0x10343e710>
print(f(1,2,3))

여기서 x,y,z 는 argument1, 2, 3 에 해당하고 expression 은 x+y+z 이다.

람다는 다음과 같이 무조건 함수로 다시 작성 할 수 있다.

def add_func(x,y,z):
	return x+y+z

람다는 표현식이므로 return을 사용할 수 없다.

2.람다는 언제 유용할까?

  1. 인라인 콜백함수를 만들 때

콜백함수란 어떤 이벤트가 발생했을때 호출되는 함수이다.
콜백함수가 여러블록으로 구성된 실행문이 아니고 다른 컴포넌트에서 사용되지 않는다면
해당 컴포넌트만을 위한 람다 표현식이 적절하다.

  1. 함수안에서 복잡한 처리를 할 수 없을 때

다음과 같은 어떤 정수에 2제곱, 3제곰, 4제곱을 하는 예제에서 함수로 구현하는 것보다 람다로 구현하는 것이 낫다.

Lambdas = [
    lambda x : x ** 2,
    lambda x : x ** 3,
    lambda x : x ** 4
]

for lambda_func in Lambdas:
    print( lambda_func(2) )

아래와 같이 간단함 함수여도 함수이름을 만들어야하고 다른 함수와 충돌이 발생할 수 있다.
람다는 함수가 사용되는 위치에 인라인 표현식으로 대체되는 간편한 방법이다.

def square(x): 
    return x ** 2

def power_3(x): 
    return x ** 3

def power_4(x):
    return x ** 4

powers = [ square, power_3, power_4 ]

for f in powers:
    print( f(2) )

Assignment

1. 다음 코드를 실행해보고 print문으로 출력되는 출력결과를 확인해보고 types 모듈에 LambdaType 외에도 어떤 타입들이 있는지 조사해 보세요.

import types

f = lambda x,y,z : x+y+z

print(f)
print(type(f))
print( type(f) == types.LambdaType)

output  
<function <lambda> at 0x7fc5a58684c0>
<class 'function'>
True

[types 모듈의 종류]

  1. types.LambdaType - The type of user-defined functions and functions created by lambda expressions.

  2. types.GeneratorType - The type of generator-iterator objects, produced by calling a generator function.

  3. types.CodeType - The type for code objects such as returned by compile().

  4. types.MethodType - The type of methods of user-defined class instances.

  5. types.BuiltinFunctionType

  6. types.BuiltinMethodType - The type of built-in functions like len() or sys.exit(), and methods of built-in classes. (Here, the term “built-in” means “written in C”.)

  7. types.ModuleType - The type of modules.

  8. types.TracebackType - The type of traceback objects such as found in sys.exc_info()[2].

  9. types.FrameType - The type of frame objects such as found in tb.tb_frame if tb is a traceback object.

  10. types.GetSetDescriptorType - The type of objects defined in extension modules with PyGetSetDef, such as FrameType.f_locals or array.array.typecode. This type is used as descriptor for object attributes; it has the same purpose as the property type, but for classes defined in extension modules.

  11. types.MemberDescriptorType - The type of objects defined in
    extension modules with PyMemberDef, such as datetime.timedelta.
    days. This type is used as descriptor for simple C data members
    which use standard conversion functions; it has the same purpose
    as the property type, but for classes defined in extension modules.

  12. types.FunctionType

2. 다음과 같이 비밀번호의 길이와 대문자가 포함된것을 확인하는 간단한 함수가 있습니다.

def check_password(password):
    if len(password) < 8:
        return 'SHORT_PASSWORD'

    if not any(c.isupper() for c in password):
        return 'NO_CAPITAL_LETTER_PASSWORD'

    return True

이함수에 있는 if문 두개를 람다표현식을 이용하여 다음과 같은 형식으로 작성해 보세요.

아래의 lambdas 리스트안에 두개의 람다표현식을 작성해야하며 주석으로 표시된 프린트가 출력결과로 나와야 합니다.

lambdas = [ lambda password : "SHORT_PASSWORD" if len(password) < 8 else "NO_CAPITAL_LETTER_PASSWORD" if not any(c.isupper() for c in password) else True ] 

#lambda 매개변수들 : 표현식1 if 조건식 else 표현식2 if 조건식 else 표현식3 

def check_password_using_lambda(password):

    for f in lambdas:
        if f(password) is not None:
            return f(password)

    return True

print( check_password_using_lambda('123') )            # SHORT_PASSWORD
print( check_password_using_lambda('12356789f') )      # NO_CAPITAL_LETTER_PASSWORD
print( check_password_using_lambda('123456789fF') )    # True
profile
꾸준히!

0개의 댓글