Python 有人能解释我为什么会被解包错误吗?

Python 有人能解释我为什么会被解包错误吗?,python,Python,我尝试创建一个包含所有4个列表的列表。然后我使用for循环遍历该列表以获取循环中的所有元素,我得到了这个错误 这是我的密码: x_train,y_train,x_test,y_test = split([1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],3) total = [x_train,y_train,x_test,y_test] for x,y,z,i in total: print(x,y,z,i) 这是我的错误: ----------------

我尝试创建一个包含所有4个列表的列表。然后我使用for循环遍历该列表以获取循环中的所有元素,我得到了这个错误

这是我的密码:

x_train,y_train,x_test,y_test = split([1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],3)
total = [x_train,y_train,x_test,y_test]
for x,y,z,i in total:
    print(x,y,z,i)
这是我的错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-43-acdb671f80e4> in <module>
     42 x_train,y_train,x_test,y_test = split([1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],3)
     43 total = [x_train,y_train,x_test,y_test]
---> 44 for x,y,z,i in total:
     45     print(x,y,z,i)
     46 

ValueError: not enough values to unpack (expected 4, got 3)

您的
for
循环逻辑不正确。循环迭代
total=[x\u-train,y\u-train,x\u-test,y\u-test]
中的每个值,并尝试将每个值解压为四个变量,
x,y,z,i
。因此,在第一次迭代中,它试图将
x_列
解包为
x,y,z,i
,但
x_列
仅包含三个值,因此出现错误消息:

ValueError: not enough values to unpack (expected 4, got 3)

我遵循了你的代码,我看到你想要找到的是这样的东西;这是正确的循环

for xtrain, xtest, ytrain, ytest in zip(total[0], total[1], total[2], total[3]):
    print( xtrain, xtest, ytrain, ytest )
我为什么要放索引?因为您的表格只是一个由4张表格组成的表格

换句话说,'total'是一个包含子数组的数组,因此我们不能将其直接放入循环中

如果可视化了'total'数组,则函数输出中的内容如下:

[array([[4, 5, 6, 7, 8, 9],
        [1, 2, 3, 7, 8, 9],
        [1, 2, 3, 4, 5, 6]], dtype=int64),
 array([[4, 5, 6, 7, 8, 9],
        [1, 2, 3, 7, 8, 9],
        [1, 2, 3, 4, 5, 6]], dtype=int64),
 array([[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]], dtype=int64),
 array([[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]], dtype=int64)]

注:

我建议您将这段代码替换为更具可读性和更优化的代码:

new_test_x  = test_array.reshape(test_array.shape[0],-1)
new_train_x = train_array_x.reshape(train_array_x.shape[0],-1)

new_train_y = train_array_y.reshape(train_array_y.shape[0],-1)
new_test_y  = test_array_y.reshape(test_array_y.shape[0],-1)
而不是你所做的:

a,b,c = test_array.shape
new_test_x = test_array.reshape(a,-1)

d,e,f = train_array_x.shape
new_train_x = train_array_x.reshape(d,-1)

g,h,i = train_array_y.shape
new_train_y = train_array_y.reshape(g,-1)

j,k,l = test_array_y.shape
new_test_y = test_array_y.reshape(j,-1)

欢迎t SO;请注意代码片段缩进,这在Python中很重要(已编辑)。
a,b,c = test_array.shape
new_test_x = test_array.reshape(a,-1)

d,e,f = train_array_x.shape
new_train_x = train_array_x.reshape(d,-1)

g,h,i = train_array_y.shape
new_train_y = train_array_y.reshape(g,-1)

j,k,l = test_array_y.shape
new_test_y = test_array_y.reshape(j,-1)