V
V
Valery Ryaboshapko2015-11-13 05:09:16
Python
Valery Ryaboshapko, 2015-11-13 05:09:16

How to economically simulate a doubly linked list in Python?

Greetings.
I need to perform certain actions with each element of the sequence. Actions depend on the value of the previous and next elements in the sequence. How to do it beautifully and in a pythonic way?
For the sake of this, you don’t really want to fence a full-fledged linked list (as recommended by Google), especially when it comes to a sequence of some modest whole or short lines. After several experiments, I built a generator that is somewhat similar to the built-in enumerate() : it takes a sequence and returns a tuple of the previous, current and next elements for each iteration. Accordingly, if there is no previous or next, then None is returned instead.

def linked(sequence):
    """
    >>> list(linked([1]))
    [(None, 1, None)]
    >>> list(linked([1, 2]))
    [(None, 1, 2), (1, 2, None)]
    >>> list(linked([1, 2, 3]))
    [(None, 1, 2), (1, 2, 3), (2, 3, None)]
    """
    index = 0
    while index < len(sequence):
        yield (sequence[index - 1] if index else None,
               sequence[index],
               sequence[index + 1] if index + 1 < len(sequence) else None)
        index += 1
    raise StopIteration

But I don’t really like this solution, it’s somehow too low-level, it gives away some kind of C.
How to do it better? Are there ready-made solutions?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Klimenko, 2015-11-13
@valerium

def previous_and_next(some_iterable):
    prevs, items, nexts = tee(some_iterable, 3)
    prevs = chain([None], prevs)
    nexts = chain(islice(nexts, 1, None), [None])
    return izip(prevs, items, nexts)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question