2017-05-29 50 views
0

输入的Python ValueError异常:值过多解压(预期2)

2 4 
1 2 3 4 
1 0 
2 1 
2 3 

我需要的对从第三行号提取到端(只从第三行2号)
这里是我的功能

def read_nodes(): 
    n, r = map(int, input().split()) 
    n_list = [] 

    for i in range(2 , n): 
     n1, n2 = map(int, input().split()) 
     n_list.append([n1, n2]) 
    return n_list 
print(read_nodes()) 

我除了[[1,0],[2,1],[2,3]] 但说 ValueError: too many values to unpack (expected 2)

+0

输入是矩阵吗? –

+0

是你的输入作为单行传递? – RomanPerekhrest

+0

第二行输入由for循环的第一次迭代处理。你在'2'开始索引的事实并没有改变这一点。 – Kendas

回答

2

有两个地方会发生这种情况

n, r = map(int, input().split()) 

n1, n2 = map(int, input().split()) 

在你假定输入只包含两个值这两种情况。如果有3或20呢?尝试类似于

for x in map(int, input().split()): 
    # code here 

或者将整个事情包装在try/except中,以至于太多的值将被干净地处理。

您的循环可能只被

for i in range(2 , n): 

    n_list.append(map(int, input().split()) 
+0

只有2号码从第三行 –

2

@ e4c5已经解释为何出现错误非常好,所以我要跳过这一部分。

如果您使用的是Python 3并且只对前两个值感兴趣,这是使用Extended Iterable Unpacking的好机会。以下是一些简短演示:

>>> n1, n2, *other = map(int, input().split()) 
1 2 3 4 
>>> n1 
1 
>>> n2 
2 
>>> other 
[3, 4] 

other是捕获剩余值的“通配符”名称。 您可以检查用户是否提供整整两个值通过检查other的truthyness:

>>> n1, n2, *other = map(int, input().split()) 
1 2 
>>> if not other: print('exactly two values') 
... 
exactly two values 

注意,这种方法仍然会抛出一个ValueError如果用户提供不到两年的数字,因为我们需要解压至少两个从列表input().split()中分配名称n1n2

+0

现在为什么我没有想到:) +1 – e4c5

相关问题