1.2 For문 #Writing Idiomatic Python 3.1

oen·2022년 1월 6일
0

1. 'index' 변수를 생성하지 말고 enumerate 함수를 사용하자

👎

l = ['a', 'b', 'c']
index = 0
for e in l:
    print(f'{index} {e}')
    index += 1

👍

l = ['a', 'b', 'c']
for index, e in enumerate(l):
    print(f'{index} {e}')

2. 'in'을 사용하자

👎

l = ['a', 'b', 'c']
index = 0
while index < len(l):
    print(l[index])
    index += 1

👍

l = ['a', 'b', 'c']
for e in l:
    print(e)

3. for-else를 사용하자

👎

for user in [{'name': 'n1', 'emails': ['a', 'b']}, {'name': 'n2', 'emails': ['c', 'd']}, {'name': 'n3', 'emails': 'e'}]:
    has_k_character = False
    for email in user.get('emails'):
        if 'k' in email:
            has_k_character = True
            print('It has k!')
            break
    if not has_k_character:
        print(f'all emails of {user.get("name")} does not include k')

👍

else 가 있으면 for 문이 break 가 된 경우 else 문은 실행되지 않는다.

for user in [{'name': 'n1', 'emails': ['a', 'b']}, {'name': 'n2', 'emails': ['c', 'd']}, {'name': 'n3', 'emails': 'e'}]:
    for email in user.get('emails'):
        if 'k' in email:
            print('It has k!')
            break
    else:
        print(f'all emails of {user.get("name")} does not include k')

It has k!
all emails of n2 does not include k
all emails of n3 does not include k

⚠️

else가 없는 경우와 비교해보자

for user in [{'name': 'n1', 'emails': ['k', 'b']}, {'name': 'n2', 'emails': ['c', 'd']}, {'name': 'n3', 'emails': 'e'}]:
    for email in user.get('emails'):
        if 'k' in email:
            print('It has k!')
            break
    # else:
    print(f'all emails of {user.get("name")} does not include k')

It has k!
all emails of n1 does not include k
all emails of n2 does not include k
all emails of n3 does not include k

profile
🐾

0개의 댓글