python将多个txt文件的内容排序并保存中位数中位数
时间: 2024-01-19 08:03:55 浏览: 28
可以使用Python中的sorted()函数对多个txt文件内容进行排序,然后找出中位数。代码示例:
```python
import glob
files = glob.glob("*.txt") # 获取当前目录下所有txt文件
contents = []
for file in files:
with open(file) as f:
content = f.readlines()
contents.extend(content)
contents = [int(x) for x in contents] # 将文件内容转为int类型
sorted_contents = sorted(contents)
if len(sorted_contents) % 2 == 0:
median_index_1 = len(sorted_contents) // 2
median_index_2 = median_index_1 - 1
median = (sorted_contents[median_index_1] + sorted_contents[median_index_2]) / 2
else:
median_index = len(sorted_contents) // 2
median = sorted_contents[median_index]
with open("median.txt", "w") as f:
f.write(str(median)) # 将中位数保存到文件
```
当然,如果文件内容过大,可以使用分块读取的方法进行处理,以免内存不足。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)