python 实现文本文件中的数字按序排序(位操作,低内存占用)

时间:2024-06-25 11:06:08

文本文件内容   ./txt

3
24
11
55
2
99
8
9
33
44

处理代码:

import sys
a = bytearray(b'')
for i in range(100):
a.append(ord('0'))
f = open('./txt','r')
line = f.readline()
while line:
try:
index = int(line)
a[index] = ord('1')
line = f.readline()
except Exception as e:
pass
f.close()
print(a)
print(sys.getsizeof(a))

 输出结果:

  bytearray(b'0011000011010000000000001000000001000000000010000000000100000000000000000000000000000000000000000001')
  161