.编写程序,求列表s=[9,8,7,3,2,1,55,6]中元素的个数,最大值、最小值、元素之和、平均值。请至少写出三种实现方法。提示:①for 循环; ②while 循环; ③list 的函数。python
时间: 2024-09-23 10:09:38 浏览: 71
当然可以,这里有三种不同的方法来实现这个需求:
1. 使用for循环和内置函数:
```python
s = [9, 8, 7, 3, 2, 1, 55, 6]
num_elements = len(s)
max_value = max(s)
min_value = min(s)
sum_values = sum(s)
# 计算平均值时需要除以元素个数,记得处理空列表的情况
try:
average_value = sum_values / num_elements
except ZeroDivisionError:
average_value = None
print("元素个数:", num_elements)
print("最大值:", max_value)
print("最小值:", min_value)
print("元素之和:", sum_values)
print("平均值:", average_value if average_value is not None else "无法计算")
```
2. 使用while循环:
```python
s = [9, 8, 7, 3, 2, 1, 55, 6]
i = 0
num_elements = i + 1 # 初始化一个计数器
max_value = s[0]
min_value = s[0]
while i < len(s):
num_elements += 1
max_value = max(max_value, s[i])
min_value = min(min_value, s[i])
i += 1
sum_values = sum(s)
average_value = sum_values / num_elements if num_elements > 0 else None
# 输出结果同上
```
3. 利用list自带函数:
```python
s = [9, 8, 7, 3, 2, 1, 55, 6]
num_elements = len(s)
max_value = max(s)
min_value = min(s)
sum_values = sum(s)
if num_elements > 0:
average_value = sum_values / num_elements
else:
average_value = None
# 输出结果同上
```
阅读全文