Python リスト要素の合計を計算
数字のリストを定義し、リスト要素の合計を計算します。
例: 入力 : [12, 15, 3, 10] 出力 : 40例 1
total = 0
list1 = [11, 5, 17, 18, 23]
for ele in range(0, len(list1)):
total = total + list1[ele]
print("リスト要素の合計は: ", total)
list1 = [11, 5, 17, 18, 23]
for ele in range(0, len(list1)):
total = total + list1[ele]
print("リスト要素の合計は: ", total)
上記の例の出力結果は次のとおりです:
列表元素之和为: 74
例 2: while() ループを使用
total = 0
ele = 0
list1 = [11, 5, 17, 18, 23]
while(ele < len(list1)):
total = total + list1[ele]
ele += 1
print("リスト要素の合計は: ", total)
ele = 0
list1 = [11, 5, 17, 18, 23]
while(ele < len(list1)):
total = total + list1[ele]
ele += 1
print("リスト要素の合計は: ", total)
上記の例の出力結果は次のとおりです:
列表元素之和为: 74
例 3: 再帰を使用
list1 = [11, 5, 17, 18, 23]
def sumOfList(list, size):
if (size == 0):
return 0
else:
return list[size - 1] + sumOfList(list, size - 1)
total = sumOfList(list1, len(list1))
print("リスト要素の合計は: ", total)
def sumOfList(list, size):
if (size == 0):
return 0
else:
return list[size - 1] + sumOfList(list, size - 1)
total = sumOfList(list1, len(list1))
print("リスト要素の合計は: ", total)
上記の例の出力結果は次のとおりです:
列表元素之和为: 74その他の拡張
Python3 例