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と同じ語源ってを覚えたのを思い出した。
それつまり覚えてないやつ。
- 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. - 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