# 用np.tile生成（n，1,2）数组-问答-阿里云开发者社区-阿里云

## 用np.tile生成（n，1,2）数组

import numpy as np

def u_vec():
return np.array([np.random.rand(1)])

n=10
u1 = np.zeros(n)

for i in range(n):

``````u1[i] = u_vec()
``````

print(u1)

def u_vec1():

``````u_vec = np.zeros((n, 2,1))
for i in range(len(u1)):
u_vec[i] += np.tile(u1[i], (2,1))
return u_vec
``````

u = u_vec1()
print(u)

[0.4594466 0.80924903 0.3186138 0.03601917 0.9116031 0.68199505
0.78999837 0.33778259 0.97626521 0.84925156]

[[[0.4594466 0.4594466]]

[[0. 0. ]]

[[0. 0. ]]

[[0. 0. ]]

[[0. 0. ]]

[[0. 0. ]]

[[0. 0. ]]

[[0. 0. ]]

[[0. 0. ]]

[[0. 0. ]]]

[[[0.4594466 0.4594466]]

[[0.3186138 0.3186138]]

[[ 0.03601917 0.03601917]]

[[ 0.9116031 0.9116031 ]]

[[0.68199505 0.68199505]]

[[0.78999837 0.78999837]]

[[0.33778259 0.33778259]]

[[0.97626521 0.97626521]]

[[0.84925156 0.84925156]]]]

Python

• 一码平川MACHEL
2019-07-17 23:26:39

问题是你的return u_vec语句被包含在for循环中。因此，只有第一个子数组使用随机值更新，其余部分u_vec保持为0，因为您在for循环的第一次迭代后立即返回。你应该用

def u_vec1():

``````u_vec = np.zeros((n, 2,1))
for i in range(len(u1)):
u_vec[i] += np.tile(u1[i], (2,1))
return u_vec # <---- moved outside the for loop``````

解决了这个问题后，您可能也有兴趣了解使用repeat和reshape获得所需结果的替代解决方案

import numpy as np

n=10
u1 = np.random.rand(n)
print(u1)

u = np.repeat(u1,2).reshape((n,2,1))
print(u)
[0.17106854 0.7346424 0.53370937 0.39838919 0.42247593 0.61545304
0.97014742 0.85912941 0.51137618 0.08148184]
[[[0.17106854]
[0.17106854]]

[[0.7346424 ]
[0.7346424 ]]

[[0.53370937]
[0.53370937]]

[[0.39838919]
[0.39838919]]

[[0.42247593]
[0.42247593]]

[[0.61545304]
[0.61545304]]

[[0.97014742]
[0.97014742]]

[[0.85912941]
[0.85912941]]

[[0.51137618]
[0.51137618]]

[[0.08148184]
[0.08148184]]]

0 0
+ 订阅