Python代码求和
时间: 2024-03-04 21:46:55 浏览: 15
以下是两种Python代码求和的例子:
1.使用sum()函数[^1]
```python
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print("Sum of numbers:", total) # 输出:15
```
2.使用reduce()函数
```python
from functools import reduce
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
print("Sum of numbers:", total) # 输出:15
```
相关问题
python加权求和代码
下面是一个简单的 Python 加权求和代码示例:
```python
numbers = [2, 5, 7, 9]
weights = [0.2, 0.3, 0.1, 0.4]
weighted_sum = sum([num * weight for num, weight in zip(numbers, weights)])
print("加权求和结果为:", weighted_sum)
```
输出:
```
加权求和结果为: 6.8
```
其中,`numbers` 是要进行加权求和的数值列表,`weights` 是对应的权重列表。使用 `zip` 函数将两个列表打包成元组的列表,然后使用列表推导式计算每个数值与其对应权重的乘积,并使用 `sum` 函数对所有乘积进行求和,得到加权求和的结果。
python累加求和代码
下面是一个简单的 Python 代码示例,用于对给定的列表进行累加求和:
```python
# 定义一个列表
my_list = [1, 2, 3, 4, 5]
# 使用 for 循环遍历列表并累加求和
total = 0
for num in my_list:
total += num
# 输出总和
print("列表中所有元素的和为:", total)
```
输出结果:
```
列表中所有元素的和为: 15
```
另外,Python还提供了内置函数`sum()`可以直接对列表进行求和,如下所示:
```python
# 定义一个列表
my_list = [1, 2, 3, 4, 5]
# 使用 sum() 函数对列表进行求和
total = sum(my_list)
# 输出总和
print("列表中所有元素的和为:", total)
```
输出结果:
```
列表中所有元素的和为: 15
```