2013-06-18 72 views
1

更多的細節轉貼..遞歸找到一個關鍵的值,直到有沒有

我遇到以下下面的代碼錯誤,基本上下面就是我要做的,下面的代碼工作正常如果只有一個值...如果值更多我得到錯誤「太多的值來解包」,我怎麼能修改我的代碼而不改變原來的目標...

  1. 如果任何值是沒有值的鍵值從輸入中刪除該行
  2. 如果任何值是具有值的鍵,爲每個值(這是鍵)遞歸地檢查它的值,直到有沒有並刪除重複的線...的樣品的輸入和輸出如下所示:

    KEY VALUES 
    353311 
    344670 
    332807 353314 
    338169 334478 
    334478 123456 34567 
    123456 98670 
    34567 11111 
    353314 353311 
    348521 350166 350168 350169 350170 
    350166 348521 
    350168 348521 
    350169 348521 
    350170 348521 
    
    EXPECTED OUTPUT 
    344670 
    332807 353314 353311 
    338169 334478 123456 34567 98670 11111 
    348521 350166 350168 350169 350170 
    

代碼: -

from collections import OrderedDict 
def main(): 
    with open('gerrit_dependencylist.txt') as f: 
     dic = OrderedDict() 
     seen = set() 
     for line in f: 
      #print dic,line 
      spl = line.split() 
      print "SPL" 
      print spl 
      if len(spl) == 1: 
       key = spl[0] 
       v = '' 
      else: 
       print "LINE" 
       print line 
       key, v = spl 
      if v in dic and dic[v] == [""]: 
       del dic[v] 
      for k1,v1 in dic.items(): 
       if key in v1: 
        dic[k1].append(v) 
        break 
      else: 
       dic[key] = [v] 

if __name__ == '__main__': 
    main() 

OUTPUT: -

LINE 
332807 353314 

LINE 
338169 334478 

LINE 
334478 123456 34567 

Traceback (most recent call last): 
    File "tesst.py", line 28, in <module> 
    main() 
    File "tesst.py", line 18, in main 
    key, v = spl 
ValueError: too many values to unpack 

回答

0

split返回一個列表。所以如果spl中有兩個以上的元素,你會得到一個ValueError

例子:

>>> a = [1,2] 
>>> b,c = a 
>>> b 
1 
>>> c 
2 
>>> a = [1,2,3] 
>>> b,c = a 

Traceback (most recent call last): 
    File "<pyshell#5>", line 1, in <module> 
    b,c = a 
ValueError: too many values to unpack 

所以,你的代碼應該是這個樣子:

key = spl[0] 
v = set(spl[1:])