Python中如何只使用10M内存对10G文件进行排序?
文件中的数据是"1,2,3,4,5,6…" 这样逗号形式分割存放的数字。
Python中如何只使用10M内存对10G文件进行排序?
28 回复
请自行完成课后作业!抖个机灵,楼下回答
用Python在10M内存下排10G文件,得用外部排序。核心思路是把大文件切成小段,每段在内存里排序后存成临时文件,最后用堆合并。
这里的关键是heapq.merge,它能按顺序合并多个已排序的迭代器,且内存占用很小。下面是一个完整示例:
import heapq
import tempfile
import os
def external_sort(input_file, output_file, chunk_size=5*1024*1024): # 5MB chunks
temp_files = []
# 1. 分割并排序
with open(input_file, 'r') as f:
chunk = []
size = 0
for line in f:
chunk.append(line)
size += len(line)
if size >= chunk_size:
chunk.sort()
temp_file = tempfile.NamedTemporaryFile(mode='w+', delete=False)
temp_file.writelines(chunk)
temp_file.flush()
temp_files.append(temp_file.name)
chunk = []
size = 0
# 处理最后一块
if chunk:
chunk.sort()
temp_file = tempfile.NamedTemporaryFile(mode='w+', delete=False)
temp_file.writelines(chunk)
temp_file.flush()
temp_files.append(temp_file.name)
# 2. 合并
streams = [open(f, 'r') for f in temp_files]
with open(output_file, 'w') as out:
for line in heapq.merge(*streams):
out.write(line)
# 清理
for s in streams:
s.close()
for f in temp_files:
os.unlink(f)
# 使用示例
external_sort('bigfile.txt', 'sorted_bigfile.txt')
要点:
- 调整
chunk_size控制内存使用(示例设为5MB,加上Python开销实际约10MB) - 文件需是文本格式,每行作为一个排序单元
- 如果数据是数字或其他类型,需在排序前转换(比如
chunk.sort(key=int))
一句话建议:用分治思想,切块排序再合并。
统计每个数字的个数,然后按照顺序打印出来……
编程珠玑了解一下
补充一点:分段读取文件
桶排序
请自行完成课后作业!
如果只给你 1k 内存你怎么排序
桶排序吧
嗯嗯,一看就是大佬,顺着你的答案,我找到了这个 https://www.cnblogs.com/LUO77/p/5838206.html
桶排序,也是一种好的方法,学习了
请大佬指点,这个题目我是今天刚遇到,真的被问住了。还是书读的少。
嗯,课后作业还不少😂
Bitmap 了解一下
文件归并排序
了解一下
如果不给你内存怎么排序
mergesort with bucket lesser than 10M
很久之前在金山面试,碰到过类似问题。。。
分段写入文件呗 内存占用少 那么 IO 占用就高咯
拿时间换空间
时间排序了解一下 :doge:
归并排序+中间结果存磁盘
不可能只有 1-9 吧
要是只有 1-9 就好办了,要是还有别的就麻烦了
就算最大的数有好几百万的,10 MB 内存也够用了。


