2016-12-14 52 views
0

我試圖建立一個程序,操縱函數(練習) - 顯示一個消息,關於當前函數來激活,獲取必要的參數輸入需要根據參數的類型和數量激活該功能,並激活它。「ValueError:太多的值來解壓」python異常時,迭代列表

當試圖運行它,我得到以下異常: ValueError異常:值過多解壓(預計3)

代碼:

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) 

我無法理解如何解決代碼,但我認爲原因是使用嵌套列表作爲循環的索引。

+0

我不知道你在想什麼'x = input(); x ='lambda x:'; exec(x)'會做。 –

+0

你可以發佈堆棧跟蹤嗎?此代碼是否有效? – TemporalWolf

+0

你對f,inp,reqtype:中的j,k,l有什麼看法?我不認爲它是這樣。 –

回答

1

我相信你是無所適從這一行做:

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

我相信你想到的是,在第一次迭代,j將採取的第一個值在fk將採取的第一個值在inpl將取reqtype中的第一個值。在第二次迭代中,j,kl中的每一個將分別取f,inpreqtype的第二值。

這不是它所做的。

嘗試此代替:

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

郵編Python Standard Library文檔,here中描述。

+0

它有幫助。但現在還有一個問題 - 「execfunc」的代碼不會返回任何內容。你有什麼想法,爲什麼?我試着打印之前會執行的命令,而且很好。 j指向該函數。此外,列表的輸入while循環在輸入「-1」時不會中斷。 –

+0

我能夠解決大部分問題,除此之外,由於某些原因,函數返回「無」。該調用是針對j的參數。 j是函數列表的迭代器。你能幫我弄清楚是什麼原因造成的嗎?另外,我很好奇 - 「zip」命令實際上做了什麼? –

+0

@גלזיגלר - 我不會推測爲什麼'j()'返回'None'。這可能值得在一個新問題中提出。我在我的答案中添加了一個鏈接到'zip()'doc。我可以建議你通過[The Python Tutorial](https://docs.python.org/3.6/tutorial/index.html)工作,並熟悉[標準庫文檔](https://docs.python .ORG/3.6 /庫/ index.html的)? –

相關問題