*Credit: Gyro Funch, Alex Martelli*

You have an iterable * p* and need to
get the

`n`

`n`

`p`

`[`

`0`

`:`

:`n`

`]`

, `p`

`[1:`

:`n`

`]`

, and so on up to
`p`

`[`

`n`

`-1:`

:`n`

`]`

.While extended slicing would return sequences of the same type
we start with, it's much more sensible to specify a `strider`

function that, instead, solves this
problem by returning a list of lists:

def strider(p, n): """ Split an iterable p into a list of n sublists, repeatedly taking the next element of p and adding it to the next sublist. Example: >>> strider('abcde', 3) [['a', 'd'], ['b', 'e'], ['c']] In other words, strider's result is equal to: [list(p[i::n]) for i in xrange(n)] if iterable p is a sequence supporting extended-slicing syntax. """ # First, prepare the result, a list of n separate lists result = [ [ ] for x in xrange(n) ] # Loop over the input, appending each item to one of # result's lists, in "round robin" fashion for i, item in enumerate(p): result[i % n].append(item) return result

The function in this recipe takes an iterable
* p* and pulls it apart into a user-defined
number

`n`

`strider`

returns a list of sublists), distributing
`p`

`n`

`n`

`p`

If we were willing to sacrifice generality, forcing argument
* p* to be a sequence supporting extended ...

Start Free Trial

No credit card required