用Python计算列表中数字的和和平均值
时间: 2023-05-29 22:03:09 浏览: 315
可以使用Python的内置函数sum()和len()来计算列表中数字的和和平均值。
示例代码:
```python
my_list = [1, 2, 3, 4, 5]
# 计算列表中数字的和
total = sum(my_list)
print("数字的和为:", total)
# 计算列表中数字的平均值
average = total / len(my_list)
print("数字的平均值为:", average)
```
输出结果:
```
数字的和为: 15
数字的平均值为: 3.0
```
相关问题
编程计算四个整数的和和平均值
以下是Python的代码示例:
```python
# 输入四个整数
num1 = int(input("请输入第一个整数:"))
num2 = int(input("请输入第二个整数:"))
num3 = int(input("请输入第三个整数:"))
num4 = int(input("请输入第四个整数:"))
# 计算和
total = num1 + num2 + num3 + num4
# 计算平均值
average = total / 4
# 输出结果
print("四个整数的和为:", total)
print("四个整数的平均值为:", average)
```
示例输出:
```
请输入第一个整数: 5
请输入第二个整数: 8
请输入第三个整数: 3
请输入第四个整数: 2
四个整数的和为: 18
四个整数的平均值为: 4.5
```
python中list求平均值
可以使用 sum() 和 len() 函数来计算 list 中所有元素的和和元素数量,然后再将和除以元素数量,即可得到 list 的平均值。代码示例:
```python
my_list = [1, 2, 3, 4, 5]
average = sum(my_list) / len(my_list)
print("List 平均值为: ", average)
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)