0

So I have a array of arrays, like

[array([-0.05504106,  4.21890792]), array([-0.05504106,  4.21890792]), array([-0.0533802 ,  4.10717668]), array([-0.0546635 ,  4.19501313])]

And what I'm attempting to do is make it into an array of 2 arrays, in which the components are put together like this:

[array([-0.05504106, -0.05504106, -.0533802, -.0546635]), array([4.21890792, 4.21890792, 4.10717668, 4.19501313])

I've tried a number of approaches. The first is as follows:

for i in range(len(array_1)-1):
zipped = zip(array_1[i], array_1[i+1], array_1[i+2])
print zipped

However, this approach has the drawback of having to add an array_1[i+n] for each additional array within array_1. Not at all practical if array_1 has many arrays within it.

The next thing I tried was attempting to use itertools.repeat in conjunction with the above code, like so:

for i in range(len(array_1)-1):
zipped = zip(itertools.repeat(array_1[i], len(array_1))
print zipped

however, this did not function the way I wanted it to.

Could you give me some idea of how I would accomplish this task? Should I be using zip and/or intertools.repeat?

2
  • so you want them to be grouped by their inner-index? basically: [(array[0][0], array[1][0], ..., array[n][0]), (array[0][1], ..., array[n][1]), ..., (array[0][m], ..., array[n][m])] ? Commented Mar 28, 2014 at 21:21
  • yes, something like that. Commented Mar 28, 2014 at 21:22

1 Answer 1

1

I am not sure which array class you are using, but with simple lists you can use zip:

a = [[-0.05504106, 4.21890792], [-0.05504106, 4.21890792], [-0.0533802, 4.10717668],[-0.0546635, 4.19501313]]

b = list(zip(*a)) #omit list in python2
print(b)

This prints:

[(-0.05504106, -0.05504106, -0.0533802, -0.0546635), (4.21890792, 4.21890792, 4.10717668, 4.19501313)]
Sign up to request clarification or add additional context in comments.

2 Comments

huh. well, thats alot easier than i thought it would be. I guess im not familiar enough with the use of the zip() function. Thanks!
@PhilipR. As a rule of thumb: zip(*x) unzips x.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.