2
3

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.

for文でデータのindexの取得

Last updated at Posted at 2019-06-29

Python言語で、コードを書いている時、とあるデータにインデックスを付与して、
データを取り出したりしたい時があるので、それについてまとめてみました。

インデックスの取得の仕方は2つあります。

###インデックスなし


animals = ['cat', 'dog', 'tiger', 'rabbit']

for animal in animals: 
    print(animal)    
実行結果
cat  dog  tiger  rabbit

animal 空の変数
###enumerate関数(index&要素取得)


animals = ['cat', 'dog', 'tiger', 'rabbit']

for i, animal in enumerate(animals):
    print(i)
    print(animal)
    print('{}:{}'.format(i, animal))
実行結果
# print(i)
  0   1   2   3

#print(animal)
  cat  dog  tiger  rabbit

#print('{}:{}'.format(i, animal))
  0:cat  1:dog  2:tiger  3:rabbit

indexを指定した数字から始めたい場合は、第二引数に数字を指定する。


for i, animal in enumerate(animals, 1):

ついでに print('{}:{}'.format(n, animal)) の.formatは format関数であり
変数の文字列への埋め込み時に使われます。また、別途記事で紹介します。

range関数(index取得)


animals = ['cat', 'dog', 'tiger', 'rabbit']

for index in range(len(animals)):
    print(index)
実行結果
  0   1   2   3

どちらの方法でもindexの取得は可能ですが、range関数はコードの可読性が低いです。
一般的にはenumerata関数を使うべき。

可読性も意識しつつ、見やすくわかりやすいコードを書く事を意識しましょう。

2
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?