Python - comprehension

강현구·2022년 3월 29일
0

Python

목록 보기
20/21

comprehension

일반적으로 list를 쉽게, 깔끔한 코드로 생성하기 위한 문법으로 사용된다.
: list comprehension

그래서, list에만 이 문법이 가능하다고 추측했으나 실제로는 Set, Dictionary 등
iterable한 객체를 만드는 것이라면 다 가능한 문법이었다.

comprehension은 크게 다음의 네가지가 있다

  • List Comprehension
  • Set Comprehension
  • Dict Comprehension
  • Generator Expression

comprehension 구문은 기본적으로 다음과 같이 사용한다 (list 기준)

# 0부터 9까지 숫자가 담긴 list A
A = [i for i in range(9)]

>>> A
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

set은 위의 list와 동일한 방법으로 만들면 된다.
dictionary도 동일한 방법으로 만들면 되나, key : value의 형태로 입력되는 값을 정의해주면 된다.

# 0부터 3까지 숫자가 키로 된 dictionary A
B = [i: True for i in range(4)]

>>> B
{0: True, 1: True, 2: True, 3: True}

generator expression

generator expression은 특별한 형태의 comprehension이다
이는 한 번에 모든 원소를 반환하지 않고 한 번에 하나의 원소만 반환하는 generator를 생성한다.
문법 자체는 다른 Comprehension과 동일하다.

gen = (x**2 for x in range(10))
print(gen)
# <generator object <genexpr> at 0x105bde5c8>
print(next(gen)) # call 1
# 0
print(next(gen)) # call 2
# 1
# 'next' 함수 호출을 10번 반복
print(next(gen)) # call 10
# 81
print(next(gen)) # call 11
"""
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
"""

Ref. https://mingrammer.com/introduce-comprehension-of-python/

profile
한걸음씩

0개의 댓글