for文の繰り返し回数にはリストをそのまま入れることができる!
し・・・知らなかった・・・。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
a = [100, 250, 300] | |
goukei = 0 | |
for i in a: | |
goukei += i | |
print (goukei) |
a = [100, 250, 300]
# aというリストを作る
goukei = 0
#goukeiという変数を作る
for i in a:
#aの要素数だけ繰り返す
goukei += i
#goukei変数にa[i]を足していく
print (goukei)
#goukeiを出力
なんて便利なんでしょう
私の今までの書き方だと↓
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
a = [100, 250, 300] | |
sum = 0 | |
for i in range(len(a)): | |
sum += a[i] | |
print (sum) |
for i in range(len(a)):
でわざわざリストの長さを取得して合計を出してますね
まぁ、やってることはまったく同じですが
さて、実際はリストの合計を出すだけなら"sum"メソッドが用意されています
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
a = [100, 200, 350] | |
print (sum(a)) |
2行。
あっさりしてますなぁ
~の倍数の値を取得【Python】リスト.append >>>
0 件のコメント:
コメントを投稿