0
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 3 years have passed since last update.

【Python】for文でインデックスを自動採番する(自分でn += 1 とかしない)方法(備忘録)

Last updated at Posted at 2021-03-22

自分用メモ

enumerate(iterable, start=0)を使う。

enumerate

そもそも enumerate(iterable, start=0)とはカウント(デフォルトは0)と、iterable上のイテレーションによって得られた値を含むタプルを返す組み込み関数。

seasons = ['Spring', 'Summer', 'Fall', 'Winter']

seasons_index_0 = list(enumerate(seasons))
seasons_index_1 = list(enumerate(seasons, 1))
seasons_index_5 = list(enumerate(seasons, 5))

print(seasons_index_0)
print(seasons_index_1)
print(seasons_index_5)

出力結果

[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
[(5, 'Spring'), (6, 'Summer'), (7, 'Fall'), (8, 'Winter')]

for文と比較すると下記1、2は等価

#1.enumerate
enumerate(seasons)

#2.for文とn += 1
def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1

enumerateを使ったインデックス付きループ

enumerateを応用してインデックス付きのループを実装する。

seasons = ['Spring', 'Summer', 'Fall', 'Winter']

for i, season in enumerate(seasons):
  print(i, "," ,season)

出力

0 , Spring
1 , Summer
2 , Fall
3 , Winter

インデックスの開始を変えるなら

seasons = ['Spring', 'Summer', 'Fall', 'Winter']

for i, season in enumerate(seasons, 5):
  print(i, "," ,season)

出力

5 , Spring
6 , Summer
7 , Fall
8 , Winter

これは便利。

応用

JSON形式の辞書リストデータに対しても実行してみる

member_list = [
    {'No': 1, 'Name': 'Yamada Taro',   'LastLoginTime': '2021-03-16 15:44:16'}, 
    {'No': 2, 'Name': 'Yamada Jiro',   'LastLoginTime': '2021-03-10 00:12:17'}, 
    {'No': 3, 'Name': 'Yamada Saburo', 'LastLoginTime': '2021-03-20 12:01:02'}, 
    {'No': 4, 'Name': 'Yamada Shiro',  'LastLoginTime': '2020-12-24 00:00:13'}, 
    {'No': 5, 'Name': 'Yamada Goro',   'LastLoginTime': '2021-03-17 11:01:55'}, 
]

for i, member in enumerate(member_list):
  print(i, "," ,member)

出力

0 , {'No': 1, 'Name': 'Yamada Taro', 'LastLoginTime': '2021-03-16 15:44:16'}
1 , {'No': 2, 'Name': 'Yamada Jiro', 'LastLoginTime': '2021-03-10 00:12:17'}
2 , {'No': 3, 'Name': 'Yamada Saburo', 'LastLoginTime': '2021-03-20 12:01:02'}
3 , {'No': 4, 'Name': 'Yamada Shiro', 'LastLoginTime': '2020-12-24 00:00:13'}
4 , {'No': 5, 'Name': 'Yamada Goro', 'LastLoginTime': '2021-03-17 11:01:55'}

問題なくインデックスを取得出来る。

参考リンク
Python docs #enumerate

以上

0
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
0
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?