한줄에 다 쓰기 (Comprehension, Expression)

bong·2022년 4월 26일

Python

목록 보기
2/9

Conditional Expression

  • if 조건문을 한줄로 쓰는 것
grade = "A" if score > 80 else "B"


List, Dict, Set Comprehension

  • list, dictionary, set를 짧게 생성할 수 있는 표현법

    [ 변수를 활용한 값 for 변수이름 in 순회가능한 객체 if 조건문 ]


a = [book["name"] for book in books]
b = [n*3 for n in num if n%2 == 0]
c = [[x*y, x+y] for x in xs
    for y in ys]

d = {item["id"] : item["value"]*3 for item in items} # items : list of dictionaries

0개의 댓글