1.2 For記事#Idiomatic Python 3.1に書き込む


1.「index」変数を作成せずに列挙関数を使用
👎
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文が切断されると、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