sat_s
sat_s

Reputation: 277

Converting a list with many items into single item lines in python

I want to convert lines in a text file from this:

animal    cat, mouse, dog, horse  
numbers    22,45,124,87

to this:

animal    cat  
animal    mouse  
animal    dog  
animal    horse  
numbers    22  
numbers    45  
numbers    124  
numbers    87

How would I do this conversion in python?

Thanks

Upvotes: 0

Views: 145

Answers (3)

Tony Veijalainen
Tony Veijalainen

Reputation: 5565

With zip you could do like this:

inp="""animal    cat, mouse, dog, horse  
numbers    22,45,124,87
"""
for line in inp.splitlines():
    key,data = line.split(None,1)
    print '\n'.join("%s%8s" % line
                    for line in zip([key.strip()] * (data.count(',')+1),
                                    (item.strip() for item in data.split(','))))

Upvotes: 0

Alex Martelli
Alex Martelli

Reputation: 882851

with open('thefile.txt') as fin:
  with open('result.txt') as fou:
    for line in fin:
      key, values = line.split(None, 1)
      vs = [x.strip() for x in values.split(',')]
      for v in vs:
          fou.write('%s    %s\n' % (key, v))

Upvotes: 4

S.Lott
S.Lott

Reputation: 392060

Use a collections.defaultdict.

You might want to search SO for similar questions.

Upvotes: 0

Related Questions