LoginSignup
2
4

More than 5 years have passed since last update.

pythonで配列/リストをfor(foreach) したときに何番目か?(indexとかkey的なもの)も習得したい。

Last updated at Posted at 2018-06-25

javascriptばっか最近かいてて、久しぶりにpython書いたら忘れてたので備忘。

結論としては 次のように記述。

for index, value in enumerate(list):

前提

pythonでlistをforすると(てかforするって言うのかな? と語彙のなさはごめんなさい)
jsのforEachみたいな感じで、勝手に中身分だけループしてくれてありがたし。

list = [ "a", "b", "c"]
for value in list:
    print(value)
# 結果
a
b
c

ただそういや何番目の値なんだ?ってindexどうやってとる?

js,PHPだと

js,PHPとかだと以下のように習得するが。。

list.forEach(function(value, index){
 //そうですもちろん私の勤め先はES5
});
foreach ($list as $key => $value){
    //なんかの処理
}

pythonはenumerate関数をつかう


list = [ "a", "b", "c"]

for index, value in enumerate(list):
     print(index, value )

# 結果
0 a
1 b
2 c

# len で配列/リストの要素数を習得する古式ゆかしき方法もあり
for i in range(len(list)):
    print i, list[i]
# ただforeach 好きの私の好みではない。

あれ? わざわざ関数かませるってなんかpythonらしくねーな。とおもったら、
このenumerate関数はイケてるのかもしれない。。

enumerate関数

開始する値を引数に指定できたりする。

for i, name in enumerate(list, 1):
    print(i, name)
# 1 a
# 2 b
# 3 c

zip(),enumerate()とかでいろんなforが回せるように、
あえてforにはindex,valueをとる仕組みがついてないのかな?

その他

なんか見覚えあるなぁーとわたしには毎度おなじみDictionary.comで調べたら、
enumuerateの語源はnumberと同じとな。
高校のときにnumerous(多数の)がnumberと同じ語源ってを覚えたのを思い出した。
それつまり覚えてないやつ。

  1. to mention separately as if in counting; name one by one; specify, as in a list: Let me enumerate the many flaws in your hypothesis.
  2. to ascertain the number of; count.

< Latin ēnumerātus (past participle of ēnumerāre), equivalent to ē- + numer(us) number + -ate

参考URL

http://www.gesource.jp/programming/python/code/0022.html
https://note.nkmk.me/python-enumerate-start/
https://python.civic-apps.com/zip-enumerate/
http://www.dictionary.com/browse/enumerate

2
4
1

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
4