Python/Fundamentals

list comprehension

metamong 2022. 3. 20.

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()와 함께 쓰이면 좋고 또 빠름!)


2차원 list

* 리스트 컴프리헨션은 2차원 list를 초기화할 때 효과적으로 사용 가능

ex) N x M 크기의 2차원 list를 한 번에 초기화할 때 매우 유용하다

 

array = [[0]*m for _ in range(n)]
#[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

 

→ 아래와 같은 code로 작성하면 x (전체 리스트 안에 포함된 각 리스트가 모두 같은 객체로 인식됨)

 

array = [[0]*m]*n
#[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

 

→ 특정한 index의 값만 바꾸어야 하는데, 위의 코드에서 만약

 

array[1][1] = 5

 

로 설정하게 된다면, for문이 아닌 *로 만들었기에, 각 리스트가 모두 같은 객체로 인식되어 값이 한번에 바뀐다.

 

array1[1][1] = 5

print(array1)
#[[0, 5, 0], [0, 5, 0], [0, 5, 0], [0, 5, 0]]

* 썸네일 출처) https://ko.m.wikipedia.org/wiki/%ED%8C%8C%EC%9D%BC:Text-x-python.svg

* 출처1) 이코테 2021

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

'Python > Fundamentals' 카테고리의 다른 글

Python Basics(1). (from Coursera)  (0) 2022.04.04
시계열 데이터 - datetime  (0) 2022.03.24
Module & Package  (0) 2022.03.19
python intro. (03)  (0) 2022.03.19
python intro. (02)  (0) 2022.03.18

댓글