递归地查找键的值,直到没有键

时间:2013-06-18 06:36:53

标签: python

重新发布更多详情..

我遇到以下错误,下面的代码,下面是我正在尝试做的事情,下面的代码工作正常,如果只有一个值...如果值更多我得到错误“太多解压缩的值“,如何在不改变原始目标的情况下修改代码......

  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  
    
  3. 代码: -

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

    输出: -

    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
    

1 个答案:

答案 0 :(得分: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:])