简体   繁体   中英

“ValueError: too many values to unpack” python exception when iterating a list of list

I was trying to build a program that manipulates functions (exercises) - shows a message about current function to activates, gets input for necessary parameters needed to activate the function, depending on the type and number of parameters, and activating it.

When trying to run it, I get the following exception: ValueError: too many values to unpack (expected 3)

The code:

s = ['Q4', 'Q5a', 'Q5b', 'Q5c', 'Q5d', 'Q6']
f = [Trapez_rule, myFilter, myFilterMulti, myPrime, isFib, repeated]
inp = [['function', 'boundry a', 'boundry b', 'parts'], ['list', 'function'], ['list', 'list of functions'], ['number'], ['number'], ['function', 'number']]
reqtype = [['f', 'n', 'n', 'n'], ['l', 'f'], ['l', 'lf'], ['n'], ['n'], ['f', 'n']]

for j, k, l in f, inp, reqtype: # for i, j, k, l in s, f, inp, reqtype:
    # print(i)
    print(j.__doc__)
    lst = []
    for w, r in k, l:
        print(w)
        if r == 'f':
            x = input()
            x = 'lambda x: '
            exec(x)
            lst.append(x) # 'x'
        elif r == 'n':
            x = input()
            lst.append(x)
        elif r == 'l':
            m = []
            x = 0
            while x != -1:
                x = input()
                m.append(x)
            lst.append(m)
        elif r == 'lf':
            m = []
            x = 0
            while x != -1:
                x = input()
                x = 'lambda x: '
                exec(x)
                m.append(x)
            lst.append(m)
    execfunc = 'j('
    for q in range(len(lst) - 1):
        execfunc += lst[q] + ', '
    execfunc += lst[q] + ')'
    exec(execfunc)

I couldn't understand how to fix the code, but I think the reason is the use of nested lists as a loop's index.

I believe you are confused about what this line does:

for j, k, l in f, inp, reqtype:

I believe you expect that, in the first iteration, j will take on the first value in f , k will take on the first value in inp , and l will take on the first value in reqtype . On the second iteration, each of j , k , and l will take on the second values of f , inp , and reqtype , respectively.

That isn't what it does.

Try this instead:

for j, k, l in zip(f, inp, reqtype):

Zip is described in the Python Standard Library documentation, here .

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