pythonでリストやタプルの合計を返す方法/sum関数の使い方

IT

excelでおなじみのsum関数では、リストなどの中にある項目を合計した数を返すことができます。

スポンサーリンク

sum関数

python len1
図のようなリストがあるとして、
#python
list = [1,2,3,4,5]
print(sum(list))
このリストをsum関数の引数に指定します。
python sum1
するとリストの中にある項目の合計である15が返されます。小数点もOKです。
python sum2
タプルにも使用可能、
python sum3
辞書の場合はキーが合計されます。
python sum4
いずれの場合も、数字以外を合計しようとするとエラーになります。
Python操作方法、関数・メソッドリファレンス
使用用途別にまとめたPythonリファレンスページです。 初期準備、基本概念 ダウンロード、インストール、起動 ShellとEditor、保存、実行 保存したPythonの起動 コメント、docstring、行またぎ コメント、...

コメント

This website stores cookies on your computer. These cookies are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to to opt-out of any future tracking, a cookie will be setup in your browser to remember this choice for one year.

Accept or Deny