python - 使用键进行内存高效排序
问题描述
我正在尝试在Python
.
i
给定一个字符串文本,我创建一个文本索引( , j
, ...) 的排序列表,其中从 开始的循环字符串i
按字典顺序小于从 开始的循环字符串j
。
我想存储循环字符串起始位置的索引,因为存储所有循环字符串会占用太多内存:len(text) * len(text)
>>> text = "hellohowareyou$"
>>> ids = [i for i in range(len(text))]
>>> ids.sort(key=lambda i: text[i:] + text[:i])
>>> print(ids)
[14, 8, 1, 10, 0, 5, 2, 3, 4, 12, 6, 9, 13, 7, 11]
>>> print([text[i:] + text[:i] for i in ids])
['$hellohowareyou', 'areyou$hellohow', 'ellohowareyou$h', 'eyou$hellohowar',
'hellohowareyou$', 'howareyou$hello', 'llohowareyou$he', 'lohowareyou$hel',
'ohowareyou$hell', 'ou$hellohowarey', 'owareyou$helloh', 'reyou$hellohowa',
'u$hellohowareyo', 'wareyou$helloho', 'you$hellohoware']
问题是,使用此代码python
会在内存中创建一个键列表,并且我的大文本内存不足。我只想python
在每次比较时创建字符串,然后再次忘记它们以使用2 * len(text)
.
有什么建议么?
解决方案
推荐阅读
- javascript - 如何使用fabricjs对文档实现黑白过滤器
- r - Shiny:编写反应式自定义函数(对数据框列执行操作)的正确语法是什么?
- android - Android Bitmap.compress 旋转图像,我需要在写入文件之前将其恢复为正常方向
- opencv - 与 opencv 一起使用的小 yolo v4 没有检测到
- windows - 有什么方法可以刷新部分非客户区吗?
- numpy - 为什么 numpy.dot() 对大值给出不正确的答案?
- python - 如何使用 Python Selenium 生成 cookie 并将其保存到文本文件中
- python - 在 Python (Pyzbar) 中利用多个 CPU 内核进行 QR 读取
- html - 使两条平行线从左右垂直位于内容的中心
- python - 熊猫从行中可用的列表数据中扩展行