-2

I have an array

r = np.zeros((5,6))
print r

whose output is

[[ 0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.]] 

I want to assign the values in this array to a list so I created a list by name grid

grid1 = [['a' for i in range (0,6)]  for j in range (0,5)]
print grid1

whose output is

[['a', 'a', 'a', 'a', 'a', 'a'], ['a', 'a', 'a', 'a', 'a', 'a'], ['a', 'a', 'a', 'a', 'a', 'a'], ['a', 'a', 'a', 'a', 'a', 'a'], ['a', 'a', 'a', 'a', 'a', 'a']]

How can I assign each value in the array to the corresponding location in list using a for loop?

I am using python 2.7

Output should be:

 [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0]]
1
  • So, you just want to convert a numpy 2d array to a list of lists? Commented Dec 19, 2015 at 5:42

3 Answers 3

6
import numpy as np
r = np.zeros((5,6))
lst = r.tolist()
Sign up to request clarification or add additional context in comments.

Comments

1

Another version, using for loops and two arrays, concatenating from the numpy array to the python list element by element:

listed = []
temp = []
r = np.zeros((5,6))

for i in r:
   for j in i:
     temp += [int(j)]
   listed += [temp]
   temp = []

print listed

listed returns

[
 [0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0], 
 [0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0]
]

...as expected.

Comments

0

Didnt fully understand. Is this what your looking for?

numbers = []
  for array in r:
    for arrayj in array:
        numbers.append(arrayj)

1 Comment

i need output in this form sir [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0]] rather than [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] which is ur codes output

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.