在python中,在一列表中随机输入1到10的10个整数,去掉最大与最小值,求剩下的平均数,保留
时间: 2024-05-08 21:14:51 浏览: 15
两位小数。
可以使用random模块中的randint函数生成1到10之间的随机整数,可以使用列表来存储这10个数,并使用min和max函数找到最小值和最大值。然后,可以使用列表的remove方法去掉最小值和最大值,最后计算平均数并将其保留两位小数。
示例代码如下:
```python
import random
# 生成10个1到10之间的随机整数
nums = [random.randint(1, 10) for _ in range(10)]
print("原始列表:", nums)
# 找到最小值和最大值
min_num = min(nums)
max_num = max(nums)
print("最小值:", min_num)
print("最大值:", max_num)
# 去掉最小值和最大值
nums.remove(min_num)
nums.remove(max_num)
print("去掉最小值和最大值后的列表:", nums)
# 计算平均数并保留两位小数
avg_num = sum(nums) / len(nums)
print("平均数:{:.2f}".format(avg_num))
```
运行结果可能如下:
```
原始列表: [8, 2, 9, 10, 10, 8, 7, 10, 10, 7]
最小值: 2
最大值: 10
去掉最小值和最大值后的列表: [8, 9, 8, 7, 7]
平均数:7.80
```
相关问题
python写一个程序:键盘输入10个整数到列表中,去掉最大值和最小值,计算剩余8个数的平均值
可以参考以下代码实现:
```python
num_list = []
for i in range(10):
num = int(input("请输入第{}个整数:".format(i+1)))
num_list.append(num)
max_num = max(num_list)
min_num = min(num_list)
num_list.remove(max_num)
num_list.remove(min_num)
avg_num = sum(num_list) / len(num_list)
print("剩余8个数的平均值为:{}".format(avg_num))
```
首先,我们定义一个空列表 `num_list`,然后使用 `for` 循环输入10个整数,并将它们添加到列表中。接着,我们使用 `max()` 和 `min()` 函数找到列表中的最大值和最小值,并使用 `remove()` 方法将它们从列表中删除。最后,我们计算剩余的8个数的平均值并输出结果。
用python.生成10个2位随机整数并输出,求其中的最大值、最小值以及10个数的平均数。
可以使用以下 Python 代码生成10个2位随机整数,并输出最大值、最小值和平均数:
```python
import random
# 生成10个2位随机整数
numbers = []
for i in range(10):
numbers.append(random.randint(10, 99))
print("生成的10个随机整数为:", numbers)
# 求最大值、最小值和平均数
max_num = max(numbers)
min_num = min(numbers)
avg_num = sum(numbers) / len(numbers)
print("最大值为:", max_num)
print("最小值为:", min_num)
print("平均数为:", avg_num)
```
首先,使用 `random.randint(10, 99)` 函数生成10个2位随机整数,并存放在列表 `numbers` 中。然后,使用 `max()` 和 `min()` 函数分别求出最大值和最小值,使用 `sum()` 函数求出所有数的和,并除以10求出平均数。最后,输出最大值、最小值和平均数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)