list/set/dict comprehension 예시



# list comprehension
print([x for x in range(5)])

print([x*2 for x in range(5) if x != 1])

print(["You are good, " + x for x in ["Zero, Jonathan"]])

#결과
#[0, 1, 2, 3, 4]
#[0, 4, 6, 8]
#['You are good, Zero, Jonathan']

# set comprehension

print({"You are good, " + x for x in ["Zero, Zero"]})

# 결과
# {'You are good, Zero, Zero'}

# dictionary comprehension
score = [('merlin', 90), ('zero', 80), ('samuel', 95)]
print({x[0]: x[1] for x in score})

# 결과
# {'merlin': 90, 'zero': 80, 'samuel': 95}


# generator expression
gen = (x+1 for x in range(5))
print(gen)
print(next(gen))
print(next(gen))
print(next(gen))

# 결과
# <generator object <genexpr> at 0x103721570>
# 1
# 2
# 3


여기에 sum을 사용해 lambda 처럼 비슷하게 사용할 수 있다. 

print([1 for x in range(5)])
#[1, 1, 1, 1, 1]

print(sum([1 for x in range(5)]))
#5


Posted by '김용환'
,