Reputation: 305
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])]
Upvotes: 3
Views: 1107
Reputation: 88226
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
Upvotes: 8
Reputation: 71560
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])]
>>>
Upvotes: 2