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()와 함께 쓰이면 좋고 또 빠름!)
'Python > Pandas&Numpy' 카테고리의 다른 글
pandas Tricks_03 👉🏻 'Convert Strings→numbers ' (Kevin by DataSchool) (0) | 2022.03.25 |
---|---|
pandas Tricks_02 👉🏻 'Select columns by Data Type' (Kevin by DataSchool) (0) | 2022.03.25 |
pandas functions - cut, qcut (0) | 2022.03.23 |
pandas Tricks_01 👉🏻 'Reverse (row/column) Order' (Kevin by DataSchool) (0) | 2022.03.23 |
Pandas (0) | 2022.03.21 |
댓글