-
Notifications
You must be signed in to change notification settings - Fork 3
Session1: SeoYeongBaek #6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| - 컴프리헨션 활용법 (리스트, 딕셔너리, 셋) | ||
|
|
||
| 컴프리헨션 | ||
|
|
||
| → 코드 간결, 가독성 높아짐 | ||
|
|
||
| **리스트 컴프리헨션** | ||
|
|
||
| - 기본 구조 | ||
|
|
||
| [expression for item in iterable if condition] | ||
|
|
||
| 1. expression : 리스트에 담을 값을 정의하는 부분 | ||
| 2. for item in iterable : 리스트 컴프리헨션이 적용될 값을 정의 | ||
|
|
||
| 2-1. iterable : 순회 가능한 객체 [리스트, 튜플] | ||
|
|
||
| 2-2. 객체에서 반복되는 요소를 받는 변수 | ||
|
|
||
| 3. if condition : 선택적으로 각 item이 이 조건을 만족할 때만 리스트에 포함 | ||
| - 특징 | ||
| 1. 간단한 반복문 처리 | ||
| 2. 조건문을 통한 필터링 | ||
| 3. 중첩된 반복문 처리 | ||
| 4. 함수 호출과 함께 사용 | ||
|
|
||
| ```python | ||
| #기존 반복문을 사용한 리스트 작성 | ||
| square = [] | ||
| for x in range(10): | ||
| squares.append(x**2) | ||
| print(squares) | ||
|
|
||
| #리스트 컴프리헨션을 사용한 리스트 생성 | ||
| squares_comp = [x**2 for x in range(10)] | ||
| print(squares_comp) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 중첩 컨프리헨션 예시도 한번 생각해보세요 |
||
| ``` | ||
|
|
||
| [https://hobbylife.tistory.com/entry/리스트-컴프리헨션-구조와-사용방법-초보자를-위한-간단한-설명과-예제#google_vignette](https://hobbylife.tistory.com/entry/%EB%A6%AC%EC%8A%A4%ED%8A%B8-%EC%BB%B4%ED%94%84%EB%A6%AC%ED%97%A8%EC%85%98-%EA%B5%AC%EC%A1%B0%EC%99%80-%EC%82%AC%EC%9A%A9%EB%B0%A9%EB%B2%95-%EC%B4%88%EB%B3%B4%EC%9E%90%EB%A5%BC-%EC%9C%84%ED%95%9C-%EA%B0%84%EB%8B%A8%ED%95%9C-%EC%84%A4%EB%AA%85%EA%B3%BC-%EC%98%88%EC%A0%9C#google_vignette) | ||
|
|
||
| **딕셔너리 컴프리헨션** | ||
|
|
||
| - 기본 구조 | ||
|
|
||
| {키_표현식 : 값_표현식 for 변수 in 반복가능한객체} | ||
|
|
||
| 1. 키_표현식 : 새로운 딕셔너리의 키를 정의하는 표현식 | ||
| 2. 값_표현식 : 해당 키에 대한 값을 정의하는 표현식 | ||
| 3. 변수 : 순회 가능한 객체에서 하나씩 요소를 가져오는 변수 | ||
|
|
||
| ```python | ||
| numbers=[1,2,3,4,5,6,7,8,9,10] | ||
| squares_dic = {x: x**2 for x in numbers} | ||
| ``` | ||
|
|
||
| https://olivia-blackcherry.tistory.com/165 | ||
|
|
||
| **셋 컴프리헨션** | ||
|
|
||
| - 기본 구조 | ||
|
|
||
| {표현식 for 표현식 in 순회가능객체} | ||
|
|
||
| - 특징 | ||
| 1. 중복 제거 | ||
|
|
||
| ```python | ||
| my_list = [1, 2, 2, 3, 4, 4, 5] | ||
| my_set = {x for x in my_list} | ||
|
|
||
| ``` | ||
|
|
||
| ```python | ||
| a_set = { n for n in range(10) if n%2==1} | ||
| ``` | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| - 언패킹과 제너레이터 | ||
|
|
||
| **언패킹** | ||
|
|
||
| : 묶여 있는 객체를 여러 개의 값으로 풀어주는 개념 | ||
|
|
||
| - 기본 구조 | ||
| 1. 가변인자를 언패킹하는 경우 , * | ||
| 2. 키워드인자를 언패킹하는 경우, ** | ||
|
|
||
| → 매개변수에서 * 을 붙이는 게 아니라 인자 앞에 *을 붙여서 사용 | ||
|
|
||
| ```python | ||
| #가변인자 언패킹 | ||
| def sum(a,b,c): | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 두 가지는 완전히 다른 개념이에요 |
||
| return a+b+c | ||
|
|
||
| numbers=[1,2,3] | ||
| print(sum(*numbers)) | ||
| ``` | ||
|
|
||
| ```python | ||
| #키워드인자 언패킹 | ||
| def cal(first,op,second): | ||
| if op=='+': | ||
| return first+second | ||
| if op=='-': | ||
| return first-second | ||
| if op=='*': | ||
| return first*second | ||
| if op=='/': | ||
| return first/second | ||
| obj={ | ||
| 'first' : 11, | ||
| 'second' : 33, | ||
| 'op' : '*' | ||
| } | ||
|
|
||
| cal(**obj) | ||
| ``` | ||
|
|
||
| https://ground90.tistory.com/131 | ||
|
|
||
| **제너레이터** | ||
|
|
||
| : iterator를 생성해 주는 함수, 일반함수와 차이는 generator함수가 실행 중 yield를 만날 경우, 해당 함수는 그 상태로 정지 되며 반환값을 next()를 호출한 쪽으로 전달하게 됨. 종료되는 것이 아니라 그 상태로 유지 | ||
|
|
||
| → 함수 내부에서 사용된 데이터들이 메모리에 유지 | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 데이터가 메모리에 유지되면 기존 변수랑은 뭐가 다를까요? 설명을 덧붙여주세요 |
||
|
|
||
| **yield : 해당 키워드 라인을 실행하고 함수를 호출한 쪽으로 프로그램의 제어를 넘겨줌 | ||
|
|
||
| - 특징 | ||
| 1. 메모리를 효율적으로 사용 | ||
|
|
||
| → 데이터의 값을 한꺼번에 메모리에 적제하는 것이 아니라 next() 메소드를 통해 차례로 값에 접근할 떄마다 메모리에 적재하는 방식 | ||
|
|
||
| 1. 계산 결과 값이 필요할 때까지 계산을 늦추는 효과 | ||
|
|
||
| ```python | ||
| def generator(n): | ||
| i=0 | ||
| while i<n: | ||
| yield i | ||
| i+=1 | ||
| for x in generator(5): | ||
| print(x) | ||
|
|
||
| ''' | ||
| 실행 중 while 문 안에서 yield 만남 | ||
| -> return 과 비슷하게 함수를 호출했던 구문으로 반환 | ||
| -> 첫번재 i 값인 0 을 반환하게 된다. | ||
| -> 반환 하였다고 generator 함수가 종료되는 것이 아니라 그대로 유지한 상태이다. | ||
| -> x 값에는 yield 에서 전달 된 0 값이 저장된 후 print | ||
| -> for 문에 의해 다시 generator 함수가 호출 | ||
| -> generator 함수가 처음부터 시작되는게 아니라 yield 이후 구문부터 시작 | ||
| -> i += 1 구문이 실행되고 i 값은 1로 증가. | ||
| -> while 문 내부이기 때문에 yield 구문을 만나 i 값인 1이 전달 | ||
| -> x 값은 1을 전달 받고 print | ||
| ''' | ||
| ``` | ||
|
|
||
| https://bluese05.tistory.com/56 | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| - 매직 메서드 (`__str__`, `__repr__`, `__eq__` 등) | ||
|
|
||
| 매직메서드 | ||
|
|
||
| :파이썬에서 사용되는 특별한 메소드 | ||
|
|
||
| == 스폐셜 메서드 | ||
|
|
||
| == 던더 메서드 | ||
|
|
||
| - `__str__` | ||
|
|
||
| : 객체를 문자열로 반환 | ||
|
|
||
| : interface로서의 역할을 수행하기 위해 존재 | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. str: 최종 사용자를 위한 읽기 쉬운 출력 |
||
|
|
||
| → 서로 다른 타입을 가진 데이터끼리 상화작용 할 때 문자열로 변환시킴으로서 상호간의 호환이 가능 | ||
|
|
||
| → 사용자에 초점 | ||
|
|
||
| ```python | ||
| #print 내부적으로 str 메서드 호출 | ||
| a = 1 | ||
| b = 'hi' | ||
| c = [1,2,3] | ||
|
|
||
| print(a,b,c) | ||
| ``` | ||
|
|
||
| - `__repr__` | ||
|
|
||
| : 객체를 문자열로 반환 | ||
|
|
||
| →객체를 문자열로 표현하기 위해 존재 | ||
|
|
||
| → 반환값은 eval 함수에 사용 가능, 새로운 객체 생성 가능 ( str의 경우 eval 사용 안됨) | ||
|
|
||
| → print() 함수가 `__str__` 메서드를 찾지 못할 때 자동으로 호출 | ||
|
|
||
| → 개발자에 초점 | ||
|
|
||
| - `__eq__` | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
|
|
||
| : 비교 매직 메서드 | ||
|
|
||
| → x == y 를 판단하는 기준을 정의 (**eq**ual to → **eq**) | ||
|
|
||
| ```python | ||
| class Str_Comparison(str): | ||
| def __new__(cls, string): | ||
| return super(Str_Comparison, cls).__new__(cls, string) | ||
| def __lt__(self, other): | ||
| return len(self) < len(other) | ||
| def __le__(self, other): | ||
| return len(self) <= len(other) | ||
| def __gt__(self, other): | ||
| return len(self) > len(other) | ||
| def __ge__(self, other): | ||
| return len(self) >= len(other) | ||
| def __eq__(self, other): | ||
| return len(self) == len(other) | ||
| def __ne__(self, other): | ||
| return len(self) != len(other) | ||
|
|
||
| s1 = Str_Comparison('Jane') | ||
| s2 = Str_Comparison('James') | ||
| s3 = Str_Comparison('Peter') | ||
| s4 = Str_Comparison('Elizabeth') | ||
|
|
||
| print(s1 < s2) # True | ||
| print('Jane' < 'James') # False | ||
|
|
||
| print(s2 == s3) # True | ||
| print('James' == 'Peter') # False | ||
|
|
||
| print(s3 < s4) # True | ||
| print('Peter' < 'Elizabeth') # False | ||
| ``` | ||
|
|
||
| https://tibetsandfox.tistory.com/39 | ||
|
|
||
| [https://supermemi.tistory.com/entry/Python-3-Magic-Methods-다루기-2편-비교-연산자-eq-ne-lt-gt-le-ge#google_vignette](https://supermemi.tistory.com/entry/Python-3-Magic-Methods-%EB%8B%A4%EB%A3%A8%EA%B8%B0-2%ED%8E%B8-%EB%B9%84%EA%B5%90-%EC%97%B0%EC%82%B0%EC%9E%90-eq-ne-lt-gt-le-ge#google_vignette) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| - 데코레이터 기초와 활용 | ||
|
|
||
| **데코레이터** | ||
|
|
||
| : 함수나 메서드에 적용되어, 해당 함수나 메서드의 기능을 확장하거나 변경하는 역할 | ||
|
|
||
| → 기본적으로 함수를 인자로 받고 또 다른 함수를 반환하는 고차 함수 | ||
|
|
||
| - 기본 구조 | ||
| 1. @기호와 함께 사용 | ||
| 2. 함수 또는 메서드 위에 위치 | ||
| - 특징 | ||
| 1. 코드 재사용성 향상 →코드의 일부분을 여러 함수에서 공유 | ||
| 2. 코드 가독성 향상 → 코드 이해하기 쉬워짐 | ||
| 3. 관심사 분리 → 함수는 핵심 기능에만 집중할 수 있음 | ||
| - 데코레이터 예제 | ||
| 1. 타이머 데코레이터 : @timer_decorator | ||
| 2. 로깅 데코레이터 : @logging_decorator | ||
| - 인자가 있는 데코레이터 예제 | ||
| 1. 함수 호출 제한 데코레이터 : @limit_calls_decorator(n) | ||
| 2. 권한 확인 데코레이터 : @permission_required_decorator(’문자열’) | ||
|
|
||
| ```python | ||
| def my_decorator(func): | ||
| def wrapper(): | ||
| print("데코레이터가 추가한 내용") | ||
| func() | ||
| print("데코레이터가 추가한 내용") | ||
| return wrapper | ||
|
|
||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. functools.wraps에 대해 찾아보면 좋을 것 같아요. |
||
| def hello(): | ||
| print("안녕하세요") | ||
|
|
||
| decorated_hello = my_decorator(hello) | ||
| decorated_hello() | ||
|
|
||
| #@기호를 이용하면 간단하고 직관적이게 코드 작성 가능, 동일한 효과 | ||
| def my_decorator(func): | ||
| def wrapper(): | ||
| print("데코레이터가 추가한 내용") | ||
| func() | ||
| print("데코레이터가 추가한 내용") | ||
| return wrapper | ||
|
|
||
| @my_decorator | ||
| def hello(): | ||
| print("안녕하세요") | ||
|
|
||
| hello() | ||
| ``` | ||
|
|
||
| [https://ctkim.tistory.com/entry/데코레이터decorator#google_vignette](https://ctkim.tistory.com/entry/%EB%8D%B0%EC%BD%94%EB%A0%88%EC%9D%B4%ED%84%B0decorator#google_vignette) | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
작동하는 코드인가요?