iterating over a list as if it were a circular list

Alexander Blinne news at blinne.net
Fri Mar 8 00:49:04 CET 2013


Am 07.03.2013 10:27, schrieb Sven:
> Now I would like to iterate over P and place one N at each point.
> However if you run out of N I'd like to restart from N[0] and carry on
> until all the points have been populated.
> So far I've got (pseudo code)
> 
> i = 0
> for point in points:
>     put N[i] at point
>     if i > len(N):
>         i = 0
> 
> is this the most pythonic way to accomplish this?

Sounds like
http://docs.python.org/3/library/itertools.html#itertools.repeat
to me.

> Additionally, what if I wanted to pull a random element from N, but I
> want to ensure all elements from N have been used before starting to
> pick already chosen random elements again.
> So far I thought of duplicating the list and removing the randomly
> chosen elements from the list, and when it's empty, re-copying it. But
> that seems a little "wrong" if you know what I mean.

This can be done with
http://docs.python.org/3/library/random.html#random.shuffle

untested:

import random

def repeated_random_permutation(iterable):
    pool = list(iterable)
    while True:
        random.shuffle(pool)
        yield from pool


Greetings



More information about the Python-list mailing list