在本教程中,我們將借助示例了解 Python sum() 方法。
sum()
函數將可迭代的項相加並返回總和。
示例
marks = [65, 71, 68, 74, 61]
# find sum of all marks
total_marks = sum(marks)
print(total_marks)
# Output: 339
sum() 語法
用法:
sum(iterable, start)
sum()
函數從左到右添加start
和給定iterable
的項目。
參數:
- iterable- 可迭代(列表、元組、字典等)。可迭代的項目應該是數字。
- start(可選)- 此值被添加到可迭代項的總和中。默認值為
start
為 0(如果省略)
返回:
sum()
返回 start
和給定 iterable
的項目的總和。
示例:Python sum() 的工作
numbers = [2.5, 3, 4, -5]
# start parameter is not provided
numbers_sum = sum(numbers)
print(numbers_sum)
# start = 10
numbers_sum = sum(numbers, 10)
print(numbers_sum)
輸出
4.5 14.5
如果您需要添加具有精確精度的浮點數,那麽您應該改用math.fsum(iterable)
。
如果您需要連接給定迭代的項目(項目必須是字符串),那麽您可以使用join()
方法。
'string'.join(sequence)
訪問此頁麵以了解Python join() Method
相關用法
- Python sum()用法及代碼示例
- Python super()用法及代碼示例
- Python scipy.ndimage.binary_opening用法及代碼示例
- Python scipy.signal.windows.tukey用法及代碼示例
- Python scipy.stats.mood用法及代碼示例
- Python scipy.fft.ihfftn用法及代碼示例
- Python scipy.stats.normaltest用法及代碼示例
- Python scipy.ndimage.convolve1d用法及代碼示例
- Python scipy.stats.arcsine用法及代碼示例
- Python scipy.interpolate.UnivariateSpline.antiderivative用法及代碼示例
- Python scipy.linalg.hadamard用法及代碼示例
- Python sympy.rf()用法及代碼示例
- Python scipy.special.inv_boxcox1p用法及代碼示例
- Python sympy.stats.GammaInverse()用法及代碼示例
- Python scipy.stats.zipfian用法及代碼示例
- Python sympy.integrals.transforms.mellin_transform()用法及代碼示例
- Python sympy.replace()用法及代碼示例
- Python scipy.stats.sampling.TransformedDensityRejection用法及代碼示例
- Python scipy.sparse.lil_array.nonzero用法及代碼示例
- Python sympy from_rgs()用法及代碼示例
注:本文由純淨天空篩選整理自 Python sum()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。