如何使一个参数在Python中显示一定次数



我有以下代码用于连接两个数组:

trainPredict = np.c_[trainPredict, np.zeros(trainPredict.shape)]

但根据一个数字,比方说n,我需要零数组显示多次,比如如果n=2:

trainPredict = np.c_[trainPredict, np.zeros(trainPredict.shape), np.zeros(trainPredict.shape)]

当我有n=2时,该代码就可以工作了,但我需要一种自动执行的方法,这样就不需要手动添加参数,这取决于n是什么。

我试着在这样的东西中使用for循环:

for i in range(0,n):
trainPredict = np.c_[trainPredict, np.zeros(trainPredict.shape)]

但它不起作用,而且我对python很陌生,所以我不确定这里发生了什么?

谢谢你的帮助!

只需一个list-comprehension并打开主中的零数组

trainPredict = np.c_[trainPredict, *[np.zeros(trainPredict.shape) for _ in range(n)]]

您可以这样做:

arr = np.zeros(trainPredict.shape)
list_.append(arr)
list_ = [arr] * n
newTrainPredict = np.array(list_)
newTrainPredict = newTrainPredict.reshape(trainPredict.shape[0], trainPredict.shape[0] * n)

最新更新