【Python 雑談・雑学】 ループ処理でインデックス番号が使いたいのなら enumerate() を使えば? 投稿一覧へ戻る
Published 2020年5月26日21:45 by T.Tsuyoshi
次のような処理をしています。
top_friends = ['Nana', 'Saki', 'Yuka']
print(f'My top 1 friend is {top_friends[0]}.')
print(f'My top 2 friend is {top_friends[1]}.')
print(f'My top 3 friend is {top_friends[2]}.')
print(f'My top 1 friend is {top_friends[0]}.')
print(f'My top 2 friend is {top_friends[1]}.')
print(f'My top 3 friend is {top_friends[2]}.')
こんなに print() 文を羅列するのではなくて for ループを使いますよね。
for i in range(3):
print(f'My top {i + 1} friend is {top_friends[i]}.')
print(f'My top {i + 1} friend is {top_friends[i]}.')
この for 文ではインデックス番号を利用してリストから値を取り出しています。
このような場合は、わざわざ range() 等を使用してインデックス番号を取得するよりも、enumerate() を利用したほうがスマートです。
for i, friend in enumerate(top_friends):
print(f'My top {i + 1} friend is {friend}.')
print(f'My top {i + 1} friend is {friend}.')
ちなみに enumerate() は generator を返します。
ですから、next() を利用して値を1つずつ取り出すことができます。
friend_g = enumerate(top_friends)
print(next(friend_g))
print(next(friend_g))
next(friend_g) で取り出される値は (index, value) からなるタプルです。
ですから当然アンパックも利用できます。
index, friend = next(friend_g)
print(index)
print(friend)
print(index)
print(friend)
こちらの投稿にも興味があるかもしれません...
- 【Python 雑談・雑学 + coding challenge】iterator protocol の実装 --- __iter__ 特殊関数は何を返すべき? イテレータオブジェクト ( iterator object ) なら何でも、そう、generator expression でもOKです!
- 【Python 雑談・雑学 + coding challenge】Unicode の正規化処理 ( normalization ) を利用して、diacritical marks ( 発音区別符号 ) を取り除こう! テキスト解析の前処理としても重要です!
- 【Python 雑談・雑学 + coding challenge】文字列中の数字を抜き出して桁区切りをつけよう! 正規表現 (regular expression ) を使うと「えっ!?」っていうくらい簡単ですょ。lookahead と negative lookahead を使います。
- 【Python 雑談・雑学 + coding challenge】sorted 組み込み関数の key パラメータをうまく使って、カスタムオブジェクトを簡単にソートしよう! __getitem__、__len__ 特殊関数 ( special methods, dunder methods ) を実装すれば立派なシーケンス ( sequence ) です
0 comments
コメントはまだありません。
コメントを追加する(不適切と思われるコメントは削除する場合があります)