Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dividing a list of arrays to a smaller list of arrays

In my current research project, I have a list of arrays similar to the one shown bellow:

import numpy as np
[np.array([ 0.00727845,  0.00363923, -0.00976286, -0.00488143]),
 np.array([ 0.00493276,  0.00246638, -0.00893927, -0.00446964]),
 np.array([ 0.00283457,  0.00141729, -0.00780608, -0.00390304]),
 np.array([ 0.00104456,  0.00052228, -0.00649412, -0.00324706]),
 np.array([-0.00040696, -0.00020348, -0.00511511, -0.00255755]),
 np.array([-0.00151502, -0.00075751, -0.00375973, -0.00187987])]

Here, the length of each individual array is the same. let it e N
Then I need to separate each array in to half and collect them separately.

That is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

list_1 = 
[np.array([ 0.00727845,  0.00363923, ]),
 np.array([ 0.00493276,  0.00246638, ]),
 np.array([ 0.00283457,  0.00141729, ]),
 np.array([ 0.00104456,  0.00052228, ]),
 np.array([-0.00040696, -0.00020348, ]),
 array([-0.00151502, -0.00075751, ])]

list_2 =
np.array([ -0.00976286, -0.00488143]),
 np.array([ -0.00893927, -0.00446964]),
 np.array([-0.00780608, -0.00390304]),
 np.array([  -0.00649412, -0.00324706]),
 np.array([ -0.00511511, -0.00255755]),
 array([ -0.00375973, -0.00187987])]

I can think of a very lengthy method using for loops to do this but I suppose there is a better way of handling. Appreciate your help

>Solution :

We could use a list comprehension approach here:

import numpy as np

inp = [
    np.array([ 0.00727845,  0.00363923, -0.00976286, -0.00488143]),
    np.array([ 0.00493276,  0.00246638, -0.00893927, -0.00446964]),
    np.array([ 0.00283457,  0.00141729, -0.00780608, -0.00390304]),
    np.array([ 0.00104456,  0.00052228, -0.00649412, -0.00324706]),
    np.array([-0.00040696, -0.00020348, -0.00511511, -0.00255755]),
    np.array([-0.00151502, -0.00075751, -0.00375973, -0.00187987])
]
list_1 = [np.array(x[0:2]) for x in inp]
list_2 = [np.array(x[2:4]) for x in inp]
print(list_1)

This prints:

 [array([0.00727845, 0.00363923]),
  array([0.00493276, 0.00246638]),
  array([0.00283457, 0.00141729]),
  array([0.00104456, 0.00052228]),
  array([-0.00040696, -0.00020348]),
  array([-0.00151502, -0.00075751])]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading