shuffling elements of a list
Alex Martelli
aleax at mac.com
Thu Jun 1 10:24:24 EDT 2006
Peter Otten <__peter__ at web.de> wrote:
> Gerard Flanagan wrote:
> > Ben Finney wrote:
>
> >> pile_index = 0
> >> for card in deck:
> >> piles[pile_index].append(card)
> >> pile_index = (pile_index + 1) % numpiles
> >
> > no need to maintain an index ;-)
> >
> > piles = [ list() for _ in range(n) ]
> > for i, card in enumerate(deck):
> > piles[i % numpiles].append(card)
>
> No need to maintain an index ;-)
>
> piles = [deck[start::numpiles] for start in range(numpiles)]
>
> Assuming deck is a list, that is.
Or, for deck hypothetically being an arbitrary iterable,
import itertools as it
piles = [ list() for _ in range(numpiles) ]
for pile, card in it.izip(it.cycle(piles), deck):
pile.append(card)
i.e., let itertools do the cycling for you. But, sure, for this problem
one can no doubt assume that deck is sliceable, and extended slicing
(==slicing with a stride) comes in handy.
Alex
More information about the Python-list
mailing list