Programming/Python
์์๋๋ฉด ์ข์ python ํจ์ - lambda, assert, map, filter
inistory
2021. 3. 25. 22:58
1. lambda()
def square(x):
return x*x
square = lambda x: x*x
books = [
"์ ๋ฐ๋ ๋ผ, 2008",
"๋ฐฑ์ค๊ณต์ฃผ, 2007",
"์ธ์ด๊ณต์ฃผ, 2020"
]
#Example 1
def get_title(row):
split = row.split(',')
return split[0]
sorted(books, key = get_title)
#Example 2
get_title = lambda row: row.split(',')[0]
sorted(books, key = get_title)
#Example 3
sorted(books, key = lambda row:row.split(',')[0])
- Example 1,2,3 ์ ๋ชจ๋ ๊ฐ์ ์ผ์ ์ํ
- lambda๋ฅผ ์ด์ฉํด ์ฝ๋๋ฅผ ์งง๊ฒ ๊ตฌํ ๊ฐ๋ฅ
2. assert()
- ๋ ๊ฐ์ง์ ๊ฐ์ด ๋์ผํ์ง ํ์ธํ๊ณ ์ถ์ ๋ ์ฌ์ฉ
- ๋ ๊ฐ์ด ๊ฐ์ผ๋ฉด ํต๊ณผ, ์๋๋ฉด ์๋ฌ
def square1(x):
return x*x
square2 = lambda x:x*x
assert(square1(3) == square(3))
- square1 ๊ณผ square2๊ฐ ๋์ผํ ๊ธฐ๋ฅ์ ์ํํ๋์ง ํ์ธ
- ๋ ๊ฐ์ด ๊ฐ์ง ์์์ ๊ฒฝ์ฐ์ assertionError ๋ฐ์
3. map()
- ์ฅ์ : ๋ฆฌ์คํธ ๋ณด๋ค ๋น ๋ฆ, ํ์์๋ ์ฐ์ฐ์ ํ์ง ์์
books = [
"์ ๋ฐ๋ ๋ผ,Cinderella, 2008",
"๋ฐฑ์ค๊ณต์ฃผ, Snow White, 2007",
"์ธ์ด๊ณต์ฃผ, The Little Mermaid, 2020"
]
#Example 1
def get_eng_title(row):
split = row.split(',')
return split[1]
eng_titles = [get_eng_title(row) for row in books]
#Example 2 : map ์ฌ์ฉ
def get_eng_title(row):
split = row.split(',')
return split[1]
eng_titles = map(get_eng_title, books) #books ๋ฆฌ์คํธ์ ์ํ ๋ชจ๋ ์์๋ค์ get_eng_title ํจ์ ๋ฐ์
#Example 3 : lambda, map ์ฌ์ฉ
eng_titles = map(lamda row: row.split(',')[1], books)
- Example2 ์์ eng_titles ์ถ๋ ฅ์, <map object at ~~~> ๋ผ๊ณ ๋ฌ๋ค(
(map์ด๋ผ๋ ํ์ ์ ์ถ๋ ฅ, ํ์์๋ ์ฐ์ฐ์ ํ์ง ์์ mapํจ์์ ํน์ง ๋๋ฌธ) - eng_titles[0] ์ด๋ฐ ์์ผ๋ก ์ถ๋ ฅํด์ผ ๊ฐ์ด ์ถ๋ ฅ ๋จ
- ๋ฆฌ์คํธ ํํ๋ก ๋ฐ๊พธ๋ฉด ๊ฒฐ๊ณผ๋ฌผ ์กฐํ ๊ฐ๋ฅ : list(eng_titles)
4. filter()
def starts_with_a(word):
return word.startswith('r')
words = ['rabbit','dog','cat', 'red']
r_words = filter(starts_with_a, words)
- print(r_word) ๋ filter ํ์ ์ ์ถ๋ ฅ
- print(list(r_word) ํํ๋ก ๋ฐ๊พธ๋ฉด ๊ฒฐ๊ณผ๋ฌผ ์กฐํ ๊ฐ๋ฅ