2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

enumerateの活用(メモ)

Posted at

リストの要素に添え字をつけるような場合、Enumerateが有効。

以下のようなリストから

qiita.py
list_monthes = ['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May', 'Jun.', 'Jul.', 'Aug', 'Sep.', 'Oct.', 'Nov.', 'Dec.']

以下のような出力を得たい。

1 : Jan.
2 : Feb.
3 : Mar.
4 : Apr.
5 : May
6 : Jun.
7 : Jul.
8 : Aug
9 : Sep.
10 : Oct.
11 : Nov.
12 : Dec.

qiita.py
for n in range(len(list_monthes)):
    month = list_monthes[n]
    print(n+1,':',month)

これで出力可能。
だが、

qiita.py
for n, month in enumerate(list_monthes,1):
    print(n,':',month)

こちらのほうが美しい。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?