python求txt文件内容中最大值最小值
时间: 2023-11-06 15:04:39 浏览: 266
最大值:
```
with open('file.txt', 'r') as file:
numbers = [int(num) for num in file.read().split()]
max_num = max(numbers)
print(max_num)
```
最小值:
```
with open('file.txt', 'r') as file:
numbers = [int(num) for num in file.read().split()]
min_num = min(numbers)
print(min_num)
```
相关问题
python中求元组的最大值最小值
Python中可以使用内置函数`max()`和`min()`来求元组的最大值和最小值。具体使用方法如下:
```
# 定义一个元组
t = (1, 2, 3, 4, 5)
# 求元组中的最大值和最小值
max_val = max(t)
min_val = min(t)
print("元组中的最大值为:", max_val)
print("元组中的最小值为:", min_val)
```
输出结果为:
```
元组中的最大值为: 5
元组中的最小值为: 1
```
python输出文件里的最大值最小值
可以使用Python的内置函数`max()`和`min()`来查找文件中的最大值和最小值。
假设要查找的文件名为`file.txt`,其中每行包含一个数字,则可以使用以下代码:
```python
with open('file.txt', 'r') as f:
numbers = [float(line.strip()) for line in f]
print("最大值:", max(numbers))
print("最小值:", min(numbers))
```
首先,使用`with open()`语句打开文件并将其读取为一个列表。使用`strip()`函数删除每行的换行符,并将每行转换为浮点数。然后,使用`max()`和`min()`函数查找列表中的最大值和最小值,并将其打印出来。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)