每次迭代将值追加到数组

时间:2020-10-28 16:53:29

标签: python arrays numpy

我正在尝试将索引存储在测试数组中的其他两个数组中。

train_idx = np.zeros(3,dtype='object')
test_dx = np.zeros(3,dtype='object')

array = np.array([1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1])
test = np.array(np.array_split(array, k))
[array([1, 0, 0, 1, 0]) array([1, 1, 1, 0]) array([1, 0, 0, 1])]

正在测试的数组,我试图将每个数组存储在不同的数组(train_index和test_index)中。

for i in range(len(test)):
    test_index = test[i]
    for j in range(len(test)):
        if i == j:
            continue
        train_index = test[j]

这个问题是,它同时存储了train_index和test_index两个数组的最后一个值

print(train_index)
print(test_index)

[1 1 1 0]
[1 0 0 1]

完整的输出如下:

[1 0 0 1 0]
[1 1 1 0]
[1 0 0 1]

[1 1 1 0]
[1 0 0 1 0]
[1 0 0 1]

[1 0 0 1]
[1 0 0 1 0]
[1 1 1 0]

我实际上想做的是将这些值附加到它们各自的数组中,我试图实现的输出如下:

test_index = [[1 0 0 1 0], [1 1 1 0], [1 0 0 1]]
train_index = [[[1 1 1 0], [1 0 0 1]], [[1 1 1 0], [1 0 0 1]],  [[1 0 0 1], [1 1 1 0]]]

1 个答案:

答案 0 :(得分:0)

将test_index和train_index定义为空列表:

test_index = []

然后使用append方法:

test_index.append(test[i])