3

I have looked around SO for similar questions, but it seems that this has only been asked for Visual Basic. What I want to do is rather simple, I guess, but being a beginner I can't seem to find the way to get it done.

I have a list of strings like this:

macrolist = ['hans', 'are', 'we', 'the', 'baddies', 'cake', 'or', 'death', 'cake', 'please', 'do', 'you', 'have', 'a', 'flag']

The problem is that this has been generated after reading from a tabbed file which has only 5 words per line, and then doing a number of changes in it (mainly shuffling). In order to generate an output file, I can join the elements of my list thus:

'\t'.join(macrolist)

...and then write it to a new file, but this will output a text file with just one line of tab-spaced items. I need to get a file which has only 5 words per line, like the original, so I thought that, before joining the list, I could insert a line break every 5 words. I've tried the following, but I get an error for "unsupported operand type(s) for /: 'str' and 'int'":

for index in macrolist:
    op = index/5
    if op is int:
        macrolist.append('\n')

print macrolist

The idea I had was that, if a given index was a multiple of 5, the code could insert a line break right afterwards. Then I could join the list and the output would be as desired. But, of course, even the design could be wrong... Any ideas?

Thanks in advance.

3 Answers3

6

Try:

def chunks(l, n):
    """ Yield successive n-sized chunks from l.
    """
    for i in xrange(0, len(l), n):
        yield l[i:i+n]
chunks(macrolist,5)

Then iterate over the lists in the list like this:

for chunk in chunks(macrolist,5):
    print '\t'.join(chunk)  

The chunks code was taken form here. I would like to thank Ned Batchelder for that code.

Community
  • 1
  • 1
user850498
  • 717
  • 1
  • 9
  • 22
  • 1
    Taken from http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python... You could quote your sources. – Emmanuel Apr 17 '12 at 09:45
  • Thanks for your answer, but that didn't seem to work, for some reason. The interpreter accepted the code, but nothing changed in the list. The above answer seems to work for me, though, so problem solved! Thanks again. – Jorge González Apr 17 '12 at 09:55
3
for i, m in enumerate(macrolist, 1):  
    outputfile.write(m + ['\t', '\n'][i % 5 == 0])
1
>>> [' '.join(macrolist[5 * i: 5 * i + 5]) for i in range(0, len(macrolist) / 5)]
['hans are we the baddies', 'cake or death cake please', 'do you have a flag']
Emmanuel
  • 13,935
  • 12
  • 50
  • 72