简体   繁体   中英

ValueError: too many values to unpack in a list

In python I have a list like below

in_list =[u'test_1,testing_1', u'test_2,testing_2', u'test_3,testing_3']

I want to print the values in this list in a loop

for test, testing in input:
    print test, testing

I get this error:

ValueError: too many values to unpack

What is the correct method?

You have a list of three values on the right side; you have only two variables on the left. Doing this assignment of a sequence (list, in your case) to a series of variables is called "unpacking". You must have a 1:1 correspondence between values and variables for this to work.

I think what you're trying to do is to iterate through comma-separated value pairs. Try something like the code below. Iterate through the three strings in your input list (use a different variable name: input is a built-in function). For each string, split it at the comma. This gives you a list of two values ... and those you can unpack.

for pair in input_list:    # "input" is a built-in function; use a different name
    test, testing = pair.split(',')
    # continue with your coding

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