Python 的 fsum 数学函数用于计算并返回可迭代对象(元组和列表)的总和。在本节中,我们将通过一个示例展示如何使用 fsum 函数。math fsum 函数的语法是
math.fsum(Iterators);
- 如果 number 参数是正数或负数,fsum 函数将计算并返回可迭代对象(元组和列表)的总和。
- 如果 number 参数不是数字,它将返回 TypeError。
Python fsum 函数示例
fsum 函数计算并返回可迭代对象的总和。在此 Python 示例中,我们将返回不同数据类型的可迭代对象的总和并显示输出。
import math
Tup = (10, 20, 12, -40 , 50) # Tuple Declaration
Lis = [-98, 32, -39, -42 , 15] # List Declaration
print('Calculating SUM of Tuple Item = %.2f' %math.fsum(Tup))
print('Calculating SUM of Tuple Item = %.2f' %math.fsum(Lis))
print('Calculating SUM of Tuple Items Directly = %.2f' %math.fsum((1, 2, 3, 4, 5)))
print('Calculating SUM of List Items Directly = %.2f' %math.fsum([10, 20, 30, 40]))
print('SUM of Decimal Tuple Items Directly = %.2f' %math.fsum((1.25, 2.45, 3.2, 4, 5.95)))
print('SUM of Decimal List Items Directly = %.2f' %math.fsum([2.45, 20.24, 3.95, 4.59]))
print('SUM of List of String Items Directly = %.2f' %math.fsum(['a', 'b', 'c', 'd']))

最后,我们尝试将此 数学函数 应用于字符串列表。正如我们之前所说,Python 会返回 TypeError 作为输出。