-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]]
RoY
  • 113
  • 1
  • 4
  • 14

3 Answers3

6
import numpy as np
r = np.zeros((5,6))
lst = r.tolist()
ilyas patanam
  • 5,116
  • 2
  • 29
  • 33
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.

Patrick Yu
  • 972
  • 1
  • 7
  • 19
0

Didnt fully understand. Is this what your looking for?

numbers = []
  for array in r:
    for arrayj in array:
        numbers.append(arrayj)
ThatPixelCherry
  • 323
  • 1
  • 4
  • 17
  • 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 – RoY Dec 19 '15 at 05:45