Python: Memory usage and optimization when modifying lists

前端 未结 7 1091
失恋的感觉
失恋的感觉 2021-02-04 03:28

The problem

My concern is the following: I am storing a relativity large dataset in a classical python list and in order to process the data I must iterate over the li

7条回答
  •  遇见更好的自我
    2021-02-04 04:12

    From your description it sounds like a deque ("deck") would be exactly what you are looking for:

    http://docs.python.org/library/collections.html#deque-objects

    "Iterate" across it by repeatedly calling pop() and then, if you want to keep the popped item in the deque, returning that item to the front with appendleft(item). To keep up with when you're done iterating and have seen everything in the deque, either put in a marker object like None that you watch for, or just ask for the deque's len() when you start a particular loop and use range() to pop() exactly that many items.

    I believe you will find all of the operations you need are then O(1).

提交回复
热议问题