假设我们有一个包含数字的列表,可以使用for循环和累加器变量来计算它们的总和。示例代码如下:
numbers = [1, 3, 7, 9, 11] total = 0 for num in numbers: total += num print("总和为:", total)
另外,如果要计算列表中元素的平均值,可以先计算总和,然后除以列表长度。示例代码如下:
numbers = [1, 3, 7, 9, 11] total = 0 for num in numbers: total += num average = total / len(numbers) print("平均值为:", average)
上一篇:不确定如何为列表计算实现