1.2 For記事#Idiomatic Python 3.1に書き込む
14303 ワード
1.「index」変数を作成せずに列挙関数を使用
👎
👎
👎
elseがある場合、for文が切断されると、else文は実行されません.
all emails of n2 does not include k
all emails of n3 does not include k
⚠️
elseがない場合に比べて
all emails of n1 does not include k
all emails of n2 does not include k
all emails of n3 does not include k
👎
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
Reference
この問題について(1.2 For記事#Idiomatic Python 3.1に書き込む), 我々は、より多くの情報をここで見つけました https://velog.io/@oen/1.2-For문-Writing-Idiomatic-Python-3.1テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol