Pythonic 한 함수를 만들어보자
Join 함수
String List를 합쳐 하나의 String으로 반환
split 함수
String type의 값을 나눠서 List 형태로 반환
# join() 함수
color = ['red', 'blue', 'green', 'yellow']
langs = ','.join(color)
print(langs)
# split() 함수
a = langs.split(',')
print('{}'.format(a))
List Comprehensions
기존 list를 사용하여 간단히 다른 list를 만드는 기법으로 포괄적인 list, 포함되는 list라는 의미로 사용된다.
일반적으로 for + append 보다 속도가 빠르다.
# general style list append
result = []
for i in range(10):
result.append(i)
print(result)
# list comprehensions
result2 = [i for i in range(10)]
print(result2)
result3 = [i for i in range(10) if i % 2 == 0]
print(result3)
# nested for loop
word_1 = 'abc'
word_2 = '1234'
result4 = [i+j for i in word_1 for j in word_2]
print(result4)
result5 = [[i+j for i in word_1] for j in word_2]
print(result5)
# zip() 함수
a, b, c = zip((1, 2, 3), (10, 20, 30), (100, 200, 300))
print(a, b, c)
# grouping same index and sum
sum_list = [sum(val) for val in zip((1, 2, 3), (10, 20, 30), (100, 200, 300))]
print(sum_list)
# enumerate zip
a_list = ['a0', 'a1', 'a2']
b_list = ['b0', 'b1', 'b2']
for i, (a, b) in enumerate(zip(a_list, b_list)):
print(i, a, b)
JS로 보는 Lambda Function
function add(x, y){
return x+y;
}
add2 = (x, y) => x + y;
my_arr = [1,2,3,4,5];
result=my_arr.map(function(item){
return item * 2
});
console.log(result);
result2 = my_arr.map(item=>item *2);
console.log(result2)
Lambda Function
함수의 이름 없이 쓸 수 있는 함수로, 수학 람다 대수에서 유래
# general function
def f(x, y):
return x + y
print(f(1, 4))
# lambda function
f = lambda x, y: x + y
print(f(1, 4))
print((lambda x: x +1)(5))
# use map function
tmp = [1, 2, 3, 4, 5]
f = lambda x: x ** 2
print(list(map(f, tmp)))
f = lambda x, y: x + y
print(list(map(f, tmp, tmp)))
tmp2 = list(map(lambda x: x ** 2 if x % 2 == 0 else x, tmp))
print(tmp2)
# use reduce function
# map function과 다르게 list에 똑같은 함수를 적용해서 통합
from functools import reduce
print(reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]))
class
# class declare
# reserved_word name(implemented obj)
class SoccerPlayer(object):
'''
@constructor SoccerPlayer
@param name
@param position
@param back_number
'''
def __init__(self, name, position, back_number):
self.name = name
self.position = position
self.back_number = back_number
# instance method
'''
@name change_back_number
@detail back_number changing
@param new_number player back_number
'''
def change_back_number(self, new_number):
print('back_number change: from {} to {}'.format(self.back_number, new_number))
self.back_number = new_number
# toString() method
'''
@overrides __str__
'''
def __str__(self):
return '{}, {}, {}'.format(self.name, self.position, self.back_number)
# instance obj
dooly = SoccerPlayer('Dooly', 'MF', 10)
# If don't have '__str__' function, print address value
print(dooly)