繁体   English   中英

Python ValueError:太多值无法解包(预期2)

[英]Python ValueError: too many values to unpack (expected 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)

有两个地方可能发生这种情况

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循环可能只是

for i in range(2 , n):

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

@ 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是捕获剩余值的“通配符”名称。 您可以检查用户是否通过检查的truthyness恰好提供两个值other

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

请注意,如果用户提供的数字少于两个,则此方法仍会引发ValueError ,因为我们需要从列表input().split()中解压缩至少两个数字,以便分配名称n1n2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM