3

How would i format a numpy array of form

data1 = np.array([[0,0,0],[0,1,1],[1,0,1],[1,1,0]])

to a list in this format:

data = [
       [[0,0], [0]],
       [[0,1], [1]],
       [[1,0], [1]],
       [[1,1], [0]]
    ] 

I tried using two for loops

for i in range(len(data)):
    for j in range(3):
       if j == 2:
            va[i] = data1[i][j]
       else:            
            sa[i] = data1[i][j]

but that gives me an index out of bounds error. I would love some ideas on how to go about this

2
  • what are va and sa initialized to? Commented Dec 8, 2013 at 6:22
  • @hpaulj va = [] and sa = [] but thank you. I got an answer to my question Commented Dec 8, 2013 at 17:22

1 Answer 1

5

Use list comprehension and slicing:

>>> data1 = np.array([[0,0,0],[0,1,1],[1,0,1],[1,1,0]])
>>> print [[x[:2].tolist(), x[2:].tolist()] for x in data1]
[[[0, 0], [0]],
 [[0, 1], [1]],
 [[1, 0], [1]],
 [[1, 1], [0]]]
Sign up to request clarification or add additional context in comments.

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.