Pythonic Code
예시: 여러 단어들을 하나로 붙일 때
colors = ['red', 'yellow', 'green', 'blue']
result = ''
for i in colors:
result += i
print(result)
colors = ['red', 'yellow', 'green', 'blue']
result = ''.join(colors)
print(result)
Why Pythonic Code?
Split 함수 : String Type의 값을 나눠서 List 형태로 변환
# 리스트에 있는 각 값을 a,b,c 변수로 unpacking
a,b,c = example.split(",")
Join 함수 : String List를 합쳐 하나의 String으로 반환할 때 사용!
word_1 = "Hello"
word_2 = "World"
result = [i+j for i in word_1 for j in word_2]
result
result = [i for i in range(10)]
result
Enumerate : List의 element를 추출할 때 번호를 붙여서 추출
for i, v in enumerate (['tic', 'tac', 'toc']):
print(i, v)
Zip : 두 개의 list의 값을 병렬적으로 추출함
alist = ['a1', 'a2', 'a3']
blist = ['b1', 'b2', 'b3']
for a, b in zip(alist, blist):
print(a, b)
Lambda : 함수 이름 없이, 함수처럼 쓸 수 있는 익명함수
f = lambda x, y: x + y
print(f(1, 4))
Map function : Sequence 자료형 각 element에 동일한 function을 적용함
ex = [1, 2, 3, 4, 5]
f = lambda x: x ** 2
print(list(map(f, ex)))
Reduce fuction : map fuction과 달리 list에 똑같은 함수를 적용해서 통합
from functools import reduce
print(reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]))
Asterisk
# *args(가변인자)
def asterisk_test(a, *args):
print(a, args)
print(type(args))
asterisk_test(1,2,3,4,5,6)
# **kargs(키워드인자)
def asterisk_test(a, **kargs):
print(a, kargs)
print(type(kargs))
asterisk_test(1, b=2, c=3, d=4, e=5, f=6)
Collections : List, Tuple, Dict에 대한 Python Built-in 확장 자료 구조(모듈)
deque : Stack과 Queue를 지원하는 모듈
from collections import deque
deque_list = deque()
for i in range(5):
deque_list.append(i)
print(deque_list)
Counter : Sequence type의 data element들의 갯수를 dict 형태로 반환
from collections import Counter
OrderedDict : Dict와 달리, 데이터를 입력한 순서대로 dict를 반환함
from collections import OrderedDict
defaultdict : Dict type의 값에 기본값을 지정, 신규값 생성시 사용하는 방법
from collections import defaultdict
namedtuple : Tuple 형태로 Data 구조체를 저장하는 방법
from collections import namedtuple