Python/Pandas&Numpy

list comprehension

metamong 2022. 3. 23.

Q. list comprehension?

 

A. list 안에 for문(+if문)을 포함시켜 편리 & 직관적인 프로그래밍 짜기

 

[f(x) for x in nums]

 

 filter condition 추가도 가능! (if문)

 

[f(x) for x in nums if g(x)]

 

→ ex) list안에 있는 element들을 한 줄만으로(👍) element 제곱형태로 표현 가능!

 

nums = [1,2,3,4]
result = [x*x for x in nums]
#result == [1,4,9,16]

 

nums = [1,2,3,4]
result = [x*x for x in nums if x%2 == 0]
#result == [4,16]

 

(+) Map + filter

 

→ ex)

 

nums = [1,2,3,4]

list(map(lambda x: x*x, nums)) # [1,4,9,16]

list(map(lambda x: x*x, filter(lambda x: x%2 == 0, nums))) # [4, 16]

 

(근데 code 보면 list comprehension이 훨 나아보임. lambda 두 번이나 쓰고 😶)


 nested list comprehension도 가능 (list comprehension 안에 또 다른 list comprehension)

→ are always preferable to for-loops with a call to .append() as they are quite faster 

(append()와 함께 쓰이면 좋고 또 빠름!)


* 출처) https://www.youtube.com/watch?v=belS2Ek4-ow&t=121s 

댓글