vendredi 8 juillet 2016

How do I combine lines in python based on a match? [on hold]


I have a file with two columns like so:

ball    small
house   big
house   small
duck    red

when the element in the 1st column appears more than once, I need to combine the elements in the 2nd column into one, spearated with '|'. Like this:

ball    small
house   big|small
duck    red

I have tried the following in python but I get an 'list index out of range' error:

f1 = open(sys.argv[1], 'rU')
lines = f1.readlines()
for i in range(0, len(lines)):
    line = lines[i]
    next_l = lines[i+1]
    splitline = line.split('t')
    splitnext = next_l.split('t')
    if splitline[0] == splitnext[0]:
        print splitline[0] + 't' + splitline[1] + '|' + splitnext[1]
    else:
        print line

Aucun commentaire:

Enregistrer un commentaire