stock = {
'못': 125,
'나사못': 35,
'나비너트': 8,
'와셔': 24,
}
order = ['나사못', '나비너트', '클립']
def get_batches(count, size):
return count // size
result = {}
for name in order:
count = stock.get(name, 0)
batches = get_batches(count, 8)
if batches:
result[name] = batches
print(result)
{'나사못': 4, '나비너트': 1}
# 딕셔너리 컴프리헨션을 사용하면 더 간결해 진다.
#
found = {name: get_batches(stock.get(name, 0), 8)
for name in order
if get_batches(stock.get(name, 0), 8)}
print(found)
#예를들어 get_batches 호출에서만 두 번째 인자를 8대신 4로 바꿨는데 결과가 달라진다.
#
has_bug = {name: get_batches(stock.get(name, 0), 4)
for name in order
if get_batches(stock.get(name, 0), 8)}
print('예상:', found)
print('실졔: ', has_bug)
예상: {'나사못': 4, '나비너트': 1}
실졔: {'나사못': 8, '나비너트': 2}
# 위 상황 예시
# if문을 지워서 첫줄 함수도 작동을 하는지 확인
#if문은 key가없는 값은 실행을 안해주는 역할일 뿐
#그렇기 때문에 아래와 같이 나옴
has_bug = {name: get_batches(stock.get(name, 0), 4)
for name in order}
print(has_bug)
{'나사못': 8, '나비너트': 2, '클립': 0}
# 왈러스를 이용
found = {name: batches for name in order
if (batches := get_batches(stock.get(name, 0), 8))}
print(found)
{'나사못': 4, '나비너트': 1}
# 오류가 나는 부분. 오류를 보고 싶으면 커멘트를 해제할것
result = {name: (tenth := count // 10)
for name, count in stock.items() if tenth > 0}
NameError Traceback (most recent call last)
in
1 # 오류가 나는 부분. 오류를 보고 싶으면 커멘트를 해제할것
----> 2 result = {name: (tenth := count // 10)
3 for name, count in stock.items() if tenth > 0}
in (.0)
1 # 오류가 나는 부분. 오류를 보고 싶으면 커멘트를 해제할것
2 result = {name: (tenth := count // 10)
----> 3 for name, count in stock.items() if tenth > 0}
NameError: name 'tenth' is not defined
result = {name: tenth for name, count in stock.items()
if (tenth := count // 10) > 0}
print(result)
print(tenth)
{'못': 12, '나사못': 3, '와셔': 2}
2
stock = {
'못': 125,
'나사못': 35,
'나비너트': 8,
'와셔': 24,
}
half = [(last := count // 2) for count in stock.values()]
print(f'{half}의 마지막 원소는 {last}')
[62, 17, 4, 12]의 마지막 원소는 12
이런 루프 변수 누출은 일반적인 for 루프에서 발생하는 루프 변수 누출과 비슷하다.
for count in stock.values(): # 루프 변수가 누출됨
pass
print(f'{list(stock.values())}의 마지막 원소는 {count}')
[125, 35, 8, 24]의 마지막 원소는 24
stock = {
'못': 125,
'나사못': 35,
'나비너트': 8,
'와셔': 24,
}
half = [count // 2 for count in stock.values()]
print(half) # 작동함
print(count) # 루프 변수가 누출되지 않기 때문에 예외가 발생함
[62, 17, 4, 12]
24
stock = {
'못': 125,
'나사못': 35,
'나비너트': 8,
'와셔': 24,
}
half=[]
for count in stock.values():
print(count)
half.append(count)
print('--------------')
print(count)
125
35
8
24
24
# 예시는 딕셔너리 인스턴스 대신 제품 이름과 현재 재고 수량 쌍으로 이뤄진 이터레이터를 만든다.
stock = {
'못': 125,
'나사못': 35,
'나비너트': 8,
'와셔': 24,
}
order = ['나사못', '나비너트', '클립']
found = ((name, batches) for name in order
if (batches := get_batches(stock.get(name, 0), 8)))
print(next(found))
print(next(found))
('나사못', 4)
('나비너트', 1)