[Python] comprehension

·2024년 3월 22일
post-thumbnail

comprehension

보통 우리는 어떤 객체에 접근하여 다른 객체의 값을 할당할 때 for문으로 접근하곤 한다.

list1=[1,2,3,4]
copy_list=[]
for num in list1:
	copy_list.append(list1)

이런 것 처럼 말이다.

하지만 comprehension 문법을 이용하면 이런 for문을 한 줄로 줄여버릴 뿐더러,
시간을 매우 단축시킬 수 있다!

사용법

[변수 for 변수 in 접근할 객체 변수에 대한 조건식]

코드를 살펴보자.

a = [i for i in range(1,11) i%2==0]
# 1부터 10까지의 수 중 짝수를 반환

이 때, comprehension은 새로운 객체를 반환하므로,
a에 리스트 형태의 객체를 할당할 수 있다.

2중 for문 comprehension 변환

그러면 2중 for문은 어떻게 쓸까??

list1=[[1,2],[3,4]]
flatten_list=[] #[1,2,3,4]를 만들고 싶음

for sublist in list1:
    for num in sublist:
        flatten_list.append(num)

를 comprehension을 바꾸게 된다면?
for문을 그냥 그대로 갖다 쓰면 된다..

flatten_list= [num for sublist in list1 for num in sublist]

그렇다면??아예 list1을 깊은 복사를 해버리고 싶다면 어떻게 할까?

copy_list1=[sublist[:] for sublist in list1]
copy_list2=[[num for num in sublist] for sublist in list1]

새로운 리스트로 감싸던가, [:]를 이용해 전체 배열을 반환하면 된다.

튜플

이런comprehension으로도 튜플의 복사가 가능하다.
그냥 대괄호 대신 괄호를 쓰면 된다!

tuple1=(1,2,3,4)
tuple2=tuple(i for i in tuple)

#마찬가지로 조건식도 맨 뒤에 붙이면 사용 가능하다
tuple3=tuple(i for i in range(1,11) i%2==0)

딕셔너리

당연히 딕셔너리로도 comprehension식 사용이 가능하다.
기본적으로 items()를 이용해야 for문을 돌 수 있는 키:값 쌍들이 만들어진다..

keys=['color','capacity','price']

dict.fromkeys(keys).items()##[{'color':None}, {'capacity':None}, {'price':None}]
cell_phone = {key:value for key,value in dict.fromkeys(keys).items()}
profile
풀스택 호소인

0개의 댓글