0

I have been trying to take elements from a array and put them into a 2d array and I was wondering if there was a way to do that?

for example

h = ['H', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'T']
a = Grid(3,3) #creates empty 2d array 

output would be

H H H
H H H
H H T

I been doing something likes this.

for row in range(a.getHeight()):
    for col in range(a.getWidth():
        for i in range(len(h):
            a[row][col] = h[i]

but i get this as the output:

T T T
T T T
T T T

2 Answers 2

4

I think I might do something like this:

hh = iter(h)
for row in range(a.getHeight()):
    for col in range(a.getWidth()):
         a[row][col] = next(hh)

This assumes that you declared a properly. In other words, a is NOT a list set up as follows:

a = [[None]*ncol]*nrow

That doesn't work since a would hold a bunch of references to the same inner list. Of course, your a isn't a simple list since it has getHeight and getWidth, so I assume whatever type of object it has taken care of that already.


If you're using numpy, this becomes almost trivial:

h = np.array(['H', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'T'])
a = h.reshape((3,3)) 
Sign up to request clarification or add additional context in comments.

1 Comment

My grid is set up using a class that takes in the values rows, columns and fillValue. self._data = Array(rows)
2

use a list comprehension:

In [11]: h = ['H', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'T']

In [12]: [h[i:i+3] for i in range(0,len(h),3)]
Out[12]: [['H', 'H', 'H'], ['H', 'H', 'H'], ['H', 'H', 'T']]

1 Comment

This won't get OP a Grid object which I assume is important. If a Grid object isn't necessary, then I support this solution.

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.