首页 > 解决方案 > 使用键进行内存高效排序

问题描述

我正在尝试在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).

有什么建议么?

标签: python

解决方案


推荐阅读