Dev/Python

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

yujin.me 2021. 7. 6. 17:13

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)

반응형