Programming Language/Python

1. Pythonic Code

HJChung 2020. 4. 3. 13:41

최근 학과 사람들과 딥러닝 학회 활동을 시작했습니다. 

저번 주는 edwith의 '[부스트코스] 머신러닝을 위한 Python'부터 시작하여 제 1장 Pythonic code 를 학습하고 나누는 시간을 가졌습니다. 

저번 주 학회를 준비해주신 분께서 너무 정리를 잘해주셔서, 애매하게 넘어갔던 부분도 다시 확실히 할 수 있었던 좋은 시간이었습니다. 

 

아래는  edwith의 '[부스트코스] 머신러닝을 위한 Python'의 '제 1장 Pythonic code' 내용을 정리한 것입니다. 

 

1) split

: 문자열-> list로 unpacking 해주는 메서드

문자열.split(나누는 기준)

example = "python, jquery, js'
example.split(',') #['python', 'jquery', 'js']

a, b, c = example.split(',')
#a='python' b='jquery' c='js'

2) join

: list->문자열 로 만들어주는 메서드

연결어.join(list명)

colors = ['red', 'blue', 'yellow']
','.join(colors) #'red,blue,yellow'

3) List Comprehension

1. 배열 안에서 for문 돌리기

result = [i for i in range(10)]
#result = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

2. list안에서 for문에 filter(조건문) 추가하기

result = [i for i in range(10) if i%2==0]
#result = [0, 2, 4, 6, 8]

3. list 안에서 2중 for문 (nested for문) 돌리기

word1 = 'Hi'
word2 = 'Ye'

result = [i+j for i in range(word1) for j in range(word2)]
#result = ['HY', 'He', 'iY', 'ie']
case1 = ['a', 'b']
case2 = ['1', '2']

result = [i+j for i in range(case1) for j in range(case2)]
#result = ['a1', 'a2', 'b1', 'b2']

4. 다차원 list: [안에 또 []쓰기]

case1 = ['a', 'b', 'c']
case2 = ['d', 'e', 'f']

result = [[i+j for i in case1]for j in case2]
#result = [['ad', 'bd', 'cd'], ['ae', 'be', 'ce'], ['af', 'bf', 'cf']]

4) enumerate

: list에서 element와 index를 추출하는 기능

for i, v in enumerate(['tic', 'tac', 'toc']):
	print(i, v)
    
#0 'tic'
#1 'tac'
#2 'toc'

1. enumerate로 unpacking하여 list 형태로 저장하는 경우

#enumerate로 unpacking하여 list 형태로 저장하는 경우, 
mylist = ['a', 'b', 'c']

list(enumerate(mylist))
#[(0, 'a'), (1, 'b'), (2, 'c')] #이렇게 tuple형태로 list에 저장됩니다. 

2. enumerate로 unpacking하여 dict 형태로 저장하는 경우 

#enumerate로 unpacking하여 dict 형태로 저장하는 경우, 
mylist = ['a', 'b', 'c']

{i:j for i, j in enumerate(mylist)}
#{0:'a', 1:'b', 2:'c'} 로 됩니다. 

5) zip

: list에서 같은 index가진 element 추출하는 기능

alist = ['a1', 'a2', 'a3']
blist = ['b1', 'b2', 'b3']

for a, b in zip(alist, blist):
	print(a, b)
 
#a1 b1
#a2 b2
#a3 b3

6) enumerate & zip

alist = ['a1', 'a2', 'a3']
blist = ['b1', 'b2', 'b3']

for i, (a, b) in enumerate(zip(alist, blist)):
	print(i, a, b)
    
#0 a1 b1
#1 a2 b2
#2 a3 b3

7) lambda

: 익명함수 (함수명을 따로 붙여주지 않아도 되는 함수 선언 방식)

#General function
def f(x, y):
	return x+y
    
#Lambda function
lambda x, y: x+y

f= lambda x, y: x+y
print(f(1, 2))

8) map

: sequence 자료형 각 element에 동일한 function을 적용하는 기능

map(functionn명, sequence 자료명)

arr = [1, 2, 3, 4, 5]
f = lambda x: x**2

print(list(map(f, arr))) #list 붙여줘야 하는 것 잊지 말자!!

1. map 함수에 조건 다는 경우

arr = [1, 2, 3, 4, 5]

list(
	map(lambda x:x**2 if x%2==0
    	else x,
        arr)
    )

9) reduce

: map 함수가 sequence 자료형에 동일한 function을 적용하는 것이었다면, reduce는 동일한 function을 적용한 후 통합까지 하는 것

from functools import reduce
print(reduce(lambda x,y: x+y, [1, 2, 3]))