How can I partially sort a Python list?

前端 未结 3 1885
孤街浪徒
孤街浪徒 2021-01-11 23:29

I wrote a compiler cache for MSVC (much like ccache for gcc). One of the things I have to do is to remove the oldest object files in my cache directory to trim the cache to

3条回答
  •  有刺的猬
    2021-01-11 23:54

    You could use the heapq module. Call heapify() on the list, followed by heappop() until your condition is met. heapify() is linear and heappop() logarithmic, so it's likely as fast as you can get.

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

    Output:

    (0, 3234)
    (1, 42341)
    

提交回复
热议问题