다른 명령
파이썬 기본기 다지기
참고 url
파이썬 언어 기본 for Finance https://www.notion.so/for-Finance-355667aea8f34c169cd7c0f705aaa875
[PY4E] 모두를 위한 프로그래밍 : 파이썬 https://www.notion.so/PY4E-7573a4454709441fa035d5237163aff0
데이터 타입 확인
# int >>> a = 3 >>> type(a) int
- float
- str
- bool
- complex
>>> c = 3 + 4j >>> type(c) complex
데이터 구조체
리스트 (LIST)
- 파이썬에는 배열은 없으며 대신에 index를 부여할 수 있는 시퀀스 타입을 제공.
- 파이썬에서 시퀀스 타입의 특징은 저장하고 있는 데이터가 순서를 가진다는 점이며, 그 중 하나가 list 타입.
- 배열과 거의 흡사하다고 볼수 있다.
- list에 담을 수 있는 타입에는 제한이 없음
- 정수, 문자열 등의 타입뿐만 아니라 모든 타입의 객체 및 다른 list 객체
my_list = [1, 'hello', 3.7, [7, 8, 9], {"a": 2, "b": 3}]
- 정수, 문자열 등의 타입뿐만 아니라 모든 타입의 객체 및 다른 list 객체
생성
>>> names = [ ] >>> names = ['a', 'b', 'c', 'd’, 'e']
또는
>>> names = list() >>> names.append('a') >>> names.append('b')
인덱싱 (indexing)
>>> names = ['a', 'b', 'c', 'd’, 'e'] >>> names[0] 'a' >>> names[1] 'b'
append (리스트 뒤에 추가)
>>> names = ['a', 'b','c'] >>> names.append('d') >>> names ['a', 'b', 'c', 'd'] >>> my_list = [1, 3, 5] >>> my_list.append(100) >>> my_list [1, 3, 5, 100] >>> my_list.append([200, 300]) >>> my_list [1, 3, 5, 100, [200, 300]]
insert (특정위치에 추가)
>>> names = ['a', 'b', 'c'] >>> names.insert(1, 'e') >>> names ['a', 'e', 'b', 'c']
확장 (extend)
- list 객체에 새로운 list를 더하여 확장.
- extend(x) 에서 x에는 iterable을 구현한 객체만 사용 가능한데, 시퀀스 타입의 자료형들은 모두 iterable을 구현했으므로 사용 가능.
- append(x) 와의 차이점은 append()는 하나의 요소로서 추가되지만 extend()는 확장 개념으로 추가된다는 점.
- 똑같은 list를 추가해보면 바로 차이점을 알 수 있음.
>>> my_list = [1, 3, 5] >>> my_list.extend([100, 200, 300]) >>> my_list [1, 3, 5, 100, 200, 300]
요소 제거 (remove)
>>> my_list = [1, 3, 1, 3] >>> my_list.remove(1) >>> my_list [3, 1, 3] >>> my_list.remove(3) >>> my_list [1, 3]
또는 DEL 키워드 사용
>>> my_list = [1, 3, 1, 3] >>> del my_list[1] >>> my_list [1, 1, 3]
list 값 꺼내기 (pop)
- list의 요소 중 끝의 요소를 꺼내어 반환.
- 복사가 아닌 꺼내는 것이기 때문에 꺼낸 요소는 list 객체에서 사라짐.
>>> my_list = [1, 3, 1, 3] >>> my_list.pop() 3 >>> my_list [1, 3, 1]
- pop(index) 로 사용하면 index 위치의 요소 값을 꺼냅니다.
>>> my_list = [1, 3, 1, 3] >>> my_list.pop(1) 3 >>> my_list [1, 1, 3]
list 정렬 (sort)
list의 요소 값들을 오름차순으로 정렬.
>>> my_list = [1, 3, 1, 3] >>> my_list.sort() >>> my_list [1, 1, 3, 3]
내림차순으로 정렬하는 경우는 reverse 값을 True.
>>> my_list = [1, 3, 1, 3] >>> my_list.sort(reverse=True) >>> my_list [3, 3, 1, 1]
list 거꾸로 뒤집기 (reverse)
list의 요소를 거꾸로.
>>> my_list = [1, 2, 3, 4] >>> my_list.reverse() >>> my_list [4, 3, 2, 1]
len(s)
>>> names = ['a', 'b', 'c', 'd, 'e'] >>> len(names) 5
COUNT list 특정 값 개수 카운트
>>> my_list = [1, 2, 3, 4, 1, 2, 3, 4] >>> my_list.count(1) 2
comprehension
- 컴프리핸션: 리스트를 한줄의 코드로 쉽게 만들때 사용
>>> data = [3, 4, 5] >>> float_data = [float(d) for d in data]
문자열을 리스트로 형변환
>>> my_str = 'python' >>> my_list = list(my_str) >>> my_list ['p', 'y', 't', 'h', 'o', 'n']
다차원 리스트
- 파이썬에서는 모든 것들이 객체이기 때문에 변수에 무엇을 집어넣든지 실제 그 객체가 들어가는 것이 아닌 객체를 가리키는 객체의 참조 주소값이 변수에 할당됩니다.
- list의 요소들도 사실은 실제 값이 아닌 요소에 할당된 객체의 주소를 가리키고 있습니다.
- 다차원 list를 만들게 되면 또 다른 list가 생성되고 그 list의 주소값을 요소로 가지고 있는 것입니다.
- 실제로는 나머지 요소들도 실제 정수 값이 아닌 정수 객체를 가리키는 주소값이 들어가 있습니다.
>>> my_list = [1, 3, 5, [11, 13, 15]] >>> my_list [1, 3, 5, [11, 13, 15]] >>> my_list[3] [11, 13, 15]
리스트 요소에 index 범위로 접근
- 파이썬에서 list같은 시퀀스 타입 자료구조의 장점은 다양한 방법으로 요소들을 접근할 수 있다는 점.
- 데이터를 다루는데, 매우 유연하게 코드를 작성할 수 있으며, 머릿속에 생각한대로 직관적으로 데이터를 다룰 수 있음.
>>> my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] >>> my_list[9:] # [9]부터 이후의 모든 요소 [10, 11, 12] >>> my_list[:4] # [4] 이전의 모든 요소 [1, 2, 3, 4] >>> my_list[::3] # 요소를 3씩 건너 뛰며 접근 [1, 4, 7, 10] >>> my_list[1:5] # [1] 부터 [5] 이전까지 [2, 3, 4, 5] >>> my_list[3::2] # [3] 부터 2씩 건너 뛰며 접근 [4, 6, 8, 10, 12]
list객체 + 연산
>>> my_list = [1, 3, 5, 7, 9] >>> my_list = my_list + my_list >>> my_list [1, 3, 5, 7, 9, 1, 3, 5, 7, 9]
list객체 * 연산
>>> my_list = [1, 3, 5, 7, 9] >>> my_list * 3 [1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 1, 3, 5, 7, 9]
list 요소 값 부분 수정
>>> my_list = [1, 3, 5, 7, 9] >>> my_list[3] = 10 >>> my_list [1, 3, 5, 10, 9]
list 요소 인덱스 범위 연산으로 수정
- 리스트[시작:끝] 범위연산을 같이 사용하면 한꺼번에 값을 수정할 수 있음.
- 주의할점은 my_list[3] = [1,2] 와 같은 식으로 수정하려 하면 범위 수정이 아닌 [3] 요소에 [1,2] list가 들어가서 [1, 3, 5, [1, 2], 9] 과 같이 2차원 list가 되어버린다는 점.
- [0:3]은 [0], [1], [2] 를 의미하므로 해당 범위를 수정하기 위해 삭제
튜플
생성
>>> names = ('a', 'b', 'c', 'd, 'e')
len(s)
>>> names = ('a', 'b', 'c', 'd, 'e') >>> len(names) 5
indexing
>>> names = ('a', 'b', 'c', 'd, 'e') >>> names[0] 'a' >>> names[1] 'b'
딕셔너리
생성
>>> cur_price = { }
insert
>>> cur_price['samsung'] = 10000 >>> cur_price {'samsung': 10000}
indexing
>>> cur_price['samsung'] >>> 10000
delete
>>> del cur_price['samsung'] >>> cur_price{}
key, value
>>> cur_price.keys() dict_keys(['samsung']) >>> cur_price.values() dict_values([10000])
기본 함수
다중 변수 print
print("City", city, 'is in the country', country)
값을 매개 변수로 전달
print("City {} is in the country {}".format(city, country))
문자열 형식 사용
순차적 옵션
print("City {} is in the country {}".format(city, country))
숫자 서식
print("City {1} is in the country {0}, yes, in {0}".format(country, city))
명시 적 이름으로 형식화
print("City {city} is in the country {country}".format(country=country, city=city))
튜플로 인수를 전달
print("City %s is in the country %s" %(city, country))
Only from Python 3.6
print(f"City {city} is in the country {country}".format(country=country, city=city))
문자열 조작 함수
len(s)
>>> mystring = "hello world" >>> len(mystring) 11
indexing
>>> mystring[0] 'h'
slicing
>>> mystring[0:5] 'hello' >>> mystring[6:] 'world'
문자열.split(S)
>>> companies = "yahoo google" >>> companies.split(' ') ['yahoo', 'google']
in
>>> 'google' in companies True
combining
>>> s1 = "hello" >>> s2 = "world" >>> s3 = s1 + ' ' + s2 >>> s3 "hello world"
replace
>>> a = "yahoo;google" >>> new_a = a.replace(';', '-') >>> new_a "yahoo-google"
index
>>> s = "yahoo google" >>> s.index("google") 6
문자열.find(x)
>>> s = "yahoo google" >>> s.find("google") 6
stripping
>>> a = " yahoo " >>> new_a = a.strip() >>> new_a "yahoo"
데이터 형변환
다음과 같이 데이터를 다른 자료형으로 Casting 할 수 있다.
>>> float(3) #실수형으로 바꿈 3.0 >>> int(3.0) #정수형으로 바꿈 3 >>> int('0xc', 16) >>> int('0o14', 8) 두 번째 인자에 입력 값의 진수를 명시하면 된다. 다른 벡터 형으로 변환할 수도 있다. >>> str(3) #문자열로 바꿈 '3' >>> hex(12) #16진수로 바꿈 '0xa' >>> oct(10) #8진수로 바꿈 '0o12' >>> bin(10) #2진수로 바꿈 '0b1010' 다시 10진수로 바꿀 때는 자동으로 바뀐다. >>> tuple([1,2]) #리스트를 튜플로 바꿈 (1, 2) >>> list((1,2)) #튜플을 리스트로 바꿈 [1, 2] >>> set([1,2]) #리스트를 집합 데이터형으로 바꿈 {1, 2}
딕셔너리로 캐스팅
- 딕셔너리로 캐스팅 하는 것은 조금 까다로운데 key 값을 어떻게 설정할 것인가를 정해야 하기 때문.
- key와 value가 한 쌍으로 된 경우 딕셔너리로 캐스팅 할 수 있다.
>>> dict([[1,2],[3,4]])#쌍으로 된 경우만 딕셔너리형으로 변환된다. {1: 2, 3: 4}
유니코드로 변환
>>> ord(‘가’) #문자를 유니코드 값으로 변환 44032 #44032는 ‘가’의 유니코드 값 >>> chr(44032). #chr()함수는 유니코드 값을 문자로 변환한다. ‘가’
파이썬 제어문
조건별 분기
if ending_price > 10000: print("sell") elif ending_price < 8000: print("buy") else: print("hold")
반복 처리
- Loop – For
>>> for i in range(0, 5): print(i) 0 1 2 3 4
>>> for i in range(0, 5): if i % 2 == 0: print(i, end=' ') 0, 2, 4 >>> buy_list = ['000660', '039490'] >>> for code in buy_list: print("buy", code) buy 000660 buy 039490 >>> hold_list = {'naver': 10, 'samsung': 20} >>> for company, num in hold_list.items(): print(company, num) naver 10 samsung 20
Loop - While
>>> i = 0 >>> while i < 5: print(i) i += 1 0 1 2 3 4 >>> i = 0 >>> while i < 5: if i % 2 == 0: print(i) i += 1 0 2 4
파이썬 모듈 임포트 방법
- 일반적인 import 방식
import os
- 필요 함수만 import 하는 방식
from os import xxx
- 모든 함수를 import 하는 방식
from os import *
변수
>>> a = 10 >>> id(a)
함수 선언
>>> def cal_upper_price(price): increment = price * 0.3 upper_price = price + increment return upper_price >>> upper_price = cal_upper_price(10000) >>> upper_price 13000
모듈
# stock.py def cal_upper_price(price): increment = price * 0.3 upper_price = price + increment return upper_price
- stock.py 모듈 import
# test.py import stock upper_price = stock.cal_upper_price(10000)
- stock.py 모듈 import
# test.py from stock import * upper_price = upper_price(10000)
클래스
- 클래스 정의(Class Definitions)
- Class: 인스턴스의 청사진 , a blueprint for an instance ("instance factories")
- Instance: 클래스의 생성된 객체 , a constructed object of the class
- Type: 인스턴스가 속한 (타입별)클래스를 가르킴 , indicates the class the instances belong to
- Attribute: 모든 객체 값 ,any object value: object.attribute
- Method: 클래스에 선언된 호출 가능한 속성 , a "callable attribute" defined in the class
인스턴스 메소드
class Joe: def callme(self): print("calling 'callme' method with instance") thisjoe = Joe() #인스턴스 할당 thisjoe.callme() #메소스 호출
클래스 정의
class BusinessCard: def __init__(self, name, email): self.name = name self.email = email def print_info(self): print(self.name) print(self.email) # instantiation and call the method mem1 = BusinessCard("Goo", "goo@gmail.com") mem1.print_info()
클래스 상속
- Class – Inheritance
>>> class Parent: def can_sing(self): print("sing a song") >>> father = Parent() >>> father.can_sing() sing a song >>> class LuckyChild(Parent): pass >>> child1 = LuckyChild() >>> child1.can_sing() sing a song >>> class LuckyChild2(Parent): def can_dance(self): print("dance beautifully") >>> child2 = LuckyChild2() >>> child2.can_sing() sing a song >>> child2.can_dance() dance beautifully
클래스 상속2
- Class – Inheritance II
>>> class Parent: def __init__(self): self.money = 10000 >>> class Child1(Parent): def __init__(self): super().__init__() >>> class Child2(Parent): def __init__(self): pass >>> child1 = Child1() #Parent의 __init__ 를 할당 받은경우 >>> child2 = Child2() #받지 않은 경우 >>> print(child1.money) 10000 >>> print(child2.money) AttributeError: 'Child2' object has no attribute 'money'