我有2个大型数组(65000,5)和(65000,2),但出于某种原因,当我在内部访问它们的循环或函数时,尺寸会随机变化。 下面是一个示例,我在for循环之前和for循环内部测试数组,结果不同。
for test_i in range(len(norm_data)):
if len(norm_data[test_i]) != norm_row_length:
print("len(norm_data[", test_i, "]) = ", len(norm_data[test_i]), " should be ", norm_row_length)
if len(vector_data[test_i]) != vector_row_length:
print("len(vector_data[", test_i, "]) = ", len(vector_data[test_i]), " should be ", vector_row_length)
for index in range(start, training_len):
x_rows = []
for prev_i in range(n_prev):
for test_i in range(len(norm_data)):
if len(norm_data[test_i]) != norm_row_length:
print("in loop len(norm_data[", test_i,"]) = ", len(norm_data[test_i]), " should be ", norm_row_length)
if len(vector_data[test_i]) != vector_row_length:
print("in loop len(vector_data[", test_i,"]) = ", len(vector_data[test_i]), " should be ", vector_row_length)
这是输出的一部分:
in loop len(norm_data[ 0 ]) = 7 should be 5
in loop len(norm_data[ 1 ]) = 9 should be 5
in loop len(norm_data[ 2 ]) = 11 should be 5
in loop len(norm_data[ 3 ]) = 13 should be 5
in loop len(norm_data[ 4 ]) = 15 should be 5
in loop len(norm_data[ 5 ]) = 15 should be 5
in loop len(norm_data[ 6 ]) = 15 should be 5
编辑: 我发现了这个问题。循环中的其余代码是修改数组。
row_index = index - (n_prev-prev_i)
x_row = norm_data[row_index]
x_row += vector_data[row_index]
x_rows.append(x_row)
这是通过引用从norm_data中获取行而不是复制它们并在之后修改它们。解决方案是复制行。
row_index = index - (n_prev-prev_i)
x_row = list(norm_data[row_index])
# or x_row = norm_data[row_index][:]
x_row += vector_data[row_index]
x_rows.append(x_row)
答案 0 :(得分:0)
跟进我的评论,这是使用enumerate()
的第一个循环的示例:
for i, row in enumerate(norm_data):
if len(row) != norm_row_length:
print("len(norm_data[{}]) = {} should be {}".format(i, len(row), norm_row_length))
if len(vector_data[i]) != vector_row_length:
print("len(vector_data[{}]) = {} should be {}".format(i, len(vector_data[i]), vector_row_length))
它还用format()
替换了这些字符串组合。它更清晰,更Pythonic。
答案 1 :(得分:0)
我发现了问题。循环中的其余代码是修改数组。
row_index = index - (n_prev-prev_i)
x_row = norm_data[row_index]
x_row += vector_data[row_index]
x_rows.append(x_row)
这是通过引用从norm_data中获取行而不是复制它们并在之后修改它们。解决方案是复制行。
row_index = index - (n_prev-prev_i)
x_row = list(norm_data[row_index])
# or x_row = norm_data[row_index][:]
x_row += vector_data[row_index]
x_rows.append(x_row)