3

Using Python 2.

I need to split an array into their rows and columns but I don't seem to get the solution as asked in the exercise

import numpy as np
a = np.array([[5, 0, 3, 3],
 [7, 9, 3, 5],
 [2, 4, 7, 6],
 [8, 8, 1, 6]])

So far I have these functions

def _rows(a):
    print("array:"+ str(a[:,]))
_rows(a)
def _col(a):
    alt=a.T
    print ("array:"+ str(alt[:,]))
_col(a)

but I need to return a list and when I use the list() function it separe each individual character

I need the result to be:

[array([5, 0, 3, 3]), array([7, 9, 3, 5]), array([2, 4, 7, 6]), array([8, 8, 1, 6])]

[array([5, 7, 2, 8]), array([0, 9, 4, 8]), array([3, 3, 7, 1]), array([3, 5, 6, 6])]

2 Answers 2

8

You can unpack the rows and columns into a list with:

res1, res2 = [*a], [*a.T]

print(res1)

[array([5, 0, 3, 3]),
 array([7, 9, 3, 5]),
 array([2, 4, 7, 6]),
 array([8, 8, 1, 6])]

print(res2)

[array([5, 7, 2, 8]),
 array([0, 9, 4, 8]),
 array([3, 3, 7, 1]),
 array([3, 5, 6, 6])]

Extended iterable unpacking was introduced in python 3.0, for older versions you can call the list constructor as in @U9-Forward 's answer

Sign up to request clarification or add additional context in comments.

6 Comments

thanks, do I have to import something to be able to use the * because it gives me a syntax error
I'm guessing you have python 2. This was introduced in python 3. Let me add some alternative for older versions @GonzalodeQuesada
thanks, I also have python 3 but I'm trying to solve an error regarding the numpy import, so, for now, I'm using python 2
Just list(a) works. [*a] doesn't work for python 3.4.4 (nor for python 2). In older python3 the error is SyntaxError: can use starred expression only as assignment target.
doesn't work for python 3.4.4 sure it does. It was introduced in python 3.0 @nicola
|
2

As it seems you're on Python 2:

>>> l1, l2 = list(a), list(a.T)
>>> l1
[array([5, 0, 3, 3]), array([7, 9, 3, 5]), array([2, 4, 7, 6]), array([8, 8, 1, 6])]
>>> l2
[array([5, 7, 2, 8]), array([0, 9, 4, 8]), array([3, 3, 7, 1]), array([3, 5, 6, 6])]
>>> 

Comments

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.