计算传入的列表的最大值、最小值和平均值,并以元组的方式返回
时间: 2024-05-12 11:19:56 浏览: 42
以下是Python代码实现:
```python
def calculate_statistics(lst):
max_val = max(lst)
min_val = min(lst)
avg_val = sum(lst) / len(lst)
return (max_val, min_val, avg_val)
# 示例
my_lst = [3, 7, 2, 9, 1, 5]
print(calculate_statistics(my_lst)) # 输出:(9, 1, 4.5)
```
其中,`max()` 和 `min()` 函数可以分别返回列表中的最大值和最小值,`sum()` 函数可以返回列表中所有元素的和,`len()` 函数可以返回列表的长度,从而计算出平均值。最后,将三个结果打包成一个元组并返回。
相关问题
计算传入的列表的最大值、最小值和平均值,并以元组的方式返回;
以下是Python代码实现:
```python
def calculate(lst):
max_val = max(lst)
min_val = min(lst)
avg_val = sum(lst) / len(lst)
return max_val, min_val, avg_val
```
使用示例:
```python
lst = [1, 2, 3, 4, 5]
result = calculate(lst)
print(result) # 输出 (5, 1, 3.0)
```
获取该元组的最大值和最小值并打印输出
假设元组为 `tup`,可以使用内置函数 `max` 和 `min` 来获取元组的最大值和最小值,然后打印输出。代码如下:
```python
tup = (3, 8, 2, 5, 1, 9, 4, 6, 7)
max_value = max(tup)
min_value = min(tup)
print("最大值为:", max_value)
print("最小值为:", min_value)
```
输出结果为:
```
最大值为: 9
最小值为: 1
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)