메서드와 함수

Finance를 위한 Python 입문

Adina Howe

Professor

메서드 vs. 함수

메서드
  • 모든 메서드는 함수입니다
  • 리스트 메서드는 Python 내장 함수의 부분집합입니다
함수
  • 모든 함수가 메서드는 아닙니다
  • 객체에 사용
    • prices.sort()
  • 객체를 입력으로 받음
    • type(prices)
Finance를 위한 Python 입문

리스트 메서드 - sort

  • 리스트에는 데이터를 조회·조작하는 내장 메서드가 있습니다
  • 메서드는 list.method()로 호출합니다

list.sort() 는 요소를 오름차순으로 정렬합니다

prices = [238.11, 237.81, 238.91]

prices.sort()
print(prices)
[237.81, 238.11, 238.91]
Finance를 위한 Python 입문

append와 extend로 리스트에 추가하기

list.append() 는 리스트에 단일 요소를 추가합니다

months = ['January', 'February', 'March']

months.append('April')
print(months)
['January', 'February', 'March', 'April']

list.extend() 는 각 요소를 개별적으로 추가합니다

months.extend(['May', 'June', 'July'])

print(months)
['January', 'February', 'March', 'April', 'May', 'June', 'July']
Finance를 위한 Python 입문

유용한 리스트 메서드 - index

list.index(x) 는 요소 x가 처음 나타나는 가장 낮은 인덱스를 반환합니다

months = ['January', 'February', 'March']
prices = [238.11, 237.81, 238.91]
months.index('February')
1
print(prices[1])
237.81
Finance를 위한 Python 입문

더 많은 함수 ...

  • min(list): 가장 작은 요소를 반환

  • max(list): 가장 큰 요소를 반환

Finance를 위한 Python 입문

최소 CPI의 월 찾기

months = ['January', 'February', 'March']
prices = [238.11, 237.81, 238.91]
# 최솟값 가격 확인
min_price = min(prices)

# 최솟값 가격의 인덱스 확인 min_index = prices.index(min_price)
# 최솟값 가격의 월 확인 min_month = months[min_index] print(min_month)
February
Finance를 위한 Python 입문

연습해봅시다!

Finance를 위한 Python 입문

Preparing Video For Download...