简体   繁体   中英

Python ValueError: too many values to unpack (expected 2)

input

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

I need to extract the pairs of numbers from third line to the end(only 2 numbers from the third line)
here is my function

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())

I except [[1,0],[2,1],[2,3]] but says ValueError: too many values to unpack (expected 2)

There are two places where this can happen

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

and

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

In both cases you are assuming that the input contains only two values. What if there are 3 or 20? Try something like

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

Or wrap the whole thing in try/except so that too many values will be handled cleanly.

Your for loop can probably just be

for i in range(2 , n):

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

@e4c5 already explained why the error occurs very well, so I am going to skip that part.

If you are using Python 3 and are only interested in the first two values, this is a good opportunity to use Extended Iterable Unpacking . Here are some short demos:

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

other is the "wildcard" name that catches the remaining values. You can check whether the user provided exactly two values by checking the truthyness of other :

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

Note that this approach will still throw a ValueError if the user supplies less than two numbers because we need to unpack at least two from the list input().split() in order to assign the names n1 and n2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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