简体   繁体   中英

Python taking elements from and array and putting them into a 2d array

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

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)) 

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']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM