如何对Python列表进行部分排序?


问题内容

我写了一个为MSVC编译器缓存(很像的ccacheGCC)。我要做的一件事是删除缓存目录中最旧的目标文件,以将缓存调整为用户定义的大小。

现在,我基本上有一个元组列表,每个元组是最后访问时间和文件大小:

# First tuple element is the access time, second tuple element is file size
items = [ (1, 42341),
          (3, 22),
          (0, 3234),
          (2, 42342),
          (4, 123) ]

现在,我想对该列表进行 部分 排序,以便对前N个元素进行排序(其中N是元素数,因此它们的大小之和超过45000)。结果基本上应该是这样的:

# Partially sorted list; only first two elements are sorted because the sum of
# their second field is larger than 45000.
items = [ (0, 3234),
          (1, 42341),
          (3, 22),
          (2, 42342),
          (4, 123) ]

我真的不在乎未排序条目的顺序,我只需要列表中N个最旧的项,其累积大小超过某个值。


问题答案:

您可以使用该heapq模块。呼叫heapify()列表,然后heappop()直到满足您的条件。heapify()是线性和heappop()对数的,因此可能会尽快获得。

heapq.heapify(items)
size = 0
while items and size < 45000:
  item = heapq.heappop(items)
  size += item[1]
  print item

输出:

(0, 3234)
(1, 42341)