Reformat list with maximum line length

Question

I have an array: foo = [1,2,3,4,5,6,7,8,9,10]
And I was wondering how best to get this array in the following form:

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

How do i do
Thank!


What am i doing now

Since it foodoes not contain several of the three elements, using numpy.reshape(), throws an error

import numpy as np
np.reshape(foo,(-1,3))

ValueError: unable to resize array 10 to form (3)

Therefore, I need to force my array to contain several of the three elements, either discarding some (but I will lose some data):

_foo = np.reshape(foo[:len(foo)-len(foo)%3],(-1,3))

print(_foo)
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Or by expanding with nan:

if len(foo)%3 != 0:
    foo.extend([np.nan]*((len(foo)%3)+1))

_foo = np.reshape(foo,(-1,3))
print(_foo)
[[ 1.  2.  3.]
 [ 4.  5.  6.]
 [ 7.  8.  9.]
 [10. nan nan]]

Notes

  • @ cᴏʟᴅsᴘᴇᴇᴅ is recommended to work with full arrays more quickly (for example, using nanor 0)
+4
source share
1

@NedBatchelder chunk generator ().

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]

lst = [1,2,3,4,5,6,7,8,9,10]

list(chunks(lst, 3))

# [[1, 2, 3],
#  [4, 5, 6],
#  [7, 8, 9],
#  [10]]
+1

Source: https://habr.com/ru/post/1694579/


All Articles