[英]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? 我一直在尝试从数组中获取元素并将其放入2d数组中,我想知道是否有办法做到这一点?
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. 这是假设你宣布
a
正确。 In other words, a
is NOT a list set up as follows: 换句话说,
a
不是按以下方式设置的列表:
a = [[None]*ncol]*nrow
That doesn't work since a
would hold a bunch of references to the same inner list . 那是行不通的,因为
a
会包含一堆对同一内部列表的引用。 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. 当然,您的
a
不是一个简单的列表,因为它具有getHeight
和getWidth
,所以我假设它已经处理了任何类型的对象。
If you're using numpy
, this becomes almost trivial: 如果您使用的是
numpy
,这将变得微不足道:
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']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.