aaronqli
aaronqli

Reputation: 809

Reshape using a shape which is not a divisible factor of length of the list

I would an easy way (preferably one line) to reshape a list

[1,2,3,4,5,6,7,8,9,10,"prime"]

into

[[1,2],[3,4],[5,6],[7,8],[9,10],["prime"]]

or

[[1,2,3],[4,5,6],[7,8,9],[10,"prime"]]

or

[[1,2,3,4],[5,6,7,8],[9,10,"prime"]]

...

as I pass different parameters (2,3,4 for examples above).

numpy.reshape cannot do that because length of the list is not divisible by 2,3,4.

Upvotes: 1

Views: 942

Answers (3)

HYRY
HYRY

Reputation: 97331

or you can use numpy.split:

data = np.array([1,2,3,4,5,6,7,8,9,10,"prime"], dtype=np.object)
np.split(data, np.r_[:len(data):3][1:])

Upvotes: 0

Gareth Latty
Gareth Latty

Reputation: 89057

Taken from the Python docs, an answer that works on any iterable:

In Python 3:

from itertools import zip_longest

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

In Python 2.x:

from itertools import izip_longest

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

Upvotes: 0

Fred Foo
Fred Foo

Reputation: 363727

>>> l = [1,2,3,4,5,6,7,8,9,10,"prime"]
>>> [l[i:i+2] for i in xrange(0, len(l), 2)]
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], ['prime']]
>>> [l[i:i+3] for i in xrange(0, len(l), 3)]
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 'prime']]
>>> [l[i:i+4] for i in xrange(0, len(l), 4)]
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 'prime']]

Upvotes: 5

Related Questions