1

I am getting the following error for below piece of code..can anyone provide inputs on how to fix it?

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[0], spl[1:]        
            for value in v:
                if value in dic and dic[value] == [""]:
                    del dic[value]
            for k1,v1 in dic.iteritems():
                if key in v1:
                    dic[k1].append(v)
                    break
            else:
                dic[key] = [v]

    with open('cherrypick_list.txt', 'w') as f:
        for k,v  in dic.items():
            f.write("{} {}\n".format(k," ".join(v)))

if __name__ == '__main__':
    main()

INPUT:-

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

CURRENT OUTPUT:-

344670 
332807 3 5 3 3 1 4 3 5 3 3 1 1
338169 3 3 4 4 7 8 1 2 3 4 5 6 3 4 5 6 7 9 8 6 7 0 1 1 1 1 1
348521 3 5 0 1 6 6 3 5 0 1 6 8 3 5 0 1 6 9 3 5 0 1 7 0 3 4 8 5 2 1 3 4 8 5 2 1 3 4 8 5 2 1 3 4 8 5 2 1
EXPECTED OUTPUT
344670
332807 353314 353311
338169 334478 123456 34567 98670 11111
348521 350166 350168 350169 350170

Error:-

Traceback (most recent call last):
  File "tesst.py", line 34, in <module>
    main()
  File "tesst.py", line 31, in main
    f.write("{} {}\n".format(k," ".join(v)))
TypeError: sequence item 0: expected string, list found
4

1 回答 1

4

除了一个 case( 344670 ['']) 之外,它的值v始终是一个列表列表,因此您需要先使用嵌套列表推导来展平列表。

with open('cherrypick_list.txt', 'w') as f:
    for k,v  in dic.items():
        val = [item if isinstance(item, str) else " ".join(item) for item in v ]
        f.write("{} {}\n".format(k,val))

获得独特的物品:

val = [item if isinstance(item, str) else " ".join(item) for item in v ]
seen = set()
val = [x for x in val if x not in seen and not seen.add(x)]
于 2013-06-18T15:54:42.997 回答