본문 바로가기

Dev/Python

[Python] 제어문과 조합하여 만들기 Comprehension

Comprehension

  • iterable한 오브젝트를 생성하기 위한 방법 중 하나
  • 파이썬에서 사용할 수 있는 유용한 기능

List Comprehension (LC)

>>> new_squares = [x**2 for x in range(10)]
>>> new_squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> new_results = [(a,b) for a in items for b in items if a != b]
>>> new_results
[('가위', '바위'), ('가위', '보'), ('바위', '가위'), ('바위', '보'), ('보', '가위'), ('보', '바위')]

Set Comprehension (SC)

>>> new_a = {x for x in 'abracadabra' if x not in 'abc'}
>>> new_a
{'d', 'r'}

Dict Comprehension (DC)

>>> new_s = { x : x ** 2 for x in (2, 4, 6)}
>>> new_s
{2: 4, 4: 16, 6: 36}

Generator Expression (GE)

반응형

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

[Python] JSON, API  (0) 2021.08.28
[Python] Pandas 데이터 프레임  (0) 2021.07.07
[Python] set()  (0) 2021.07.06
[Python] list에 다른 변수 할당할 경우 주의할 점  (0) 2021.07.05
[Python] format()  (0) 2021.07.03