9

Possible Duplicate:
How do you split a list into evenly sized chunks in Python?
Merge two lists in python?

Original data in array:

a = ['1', '2', '3', '4', '5', '6', '7', '8', '9']

Desired output:

['1 2 3', '4 5 6', '7 8 9']

I know using the while statement is inefficient, so I need help in this.

9
  • What have you tried so far? Are you trying to merge groups of always three columns? Commented Sep 6, 2012 at 6:08
  • Your title doesn't seem to match the rest of the question. There's only one array, it seems, not three. Do you really want to turn the list of strings into lists of longer strings that join three adjacent elements, or do you really need something different? Commented Sep 6, 2012 at 6:13
  • 1
    @Blckknght: His username is Natsume - English is more than likely not his native tongue. Additionally, his question does not seem ambiguous to me. Commented Sep 6, 2012 at 6:17
  • im not good in english sorry :P Commented Sep 6, 2012 at 6:17
  • 1
    The biggest inefficiency, in my opinion, would be to spend too much time trying to find the "best" way to do something. Time is often worth alot more than a few processor cycles. Commented Sep 6, 2012 at 6:30

2 Answers 2

19
[' '.join(a[i:i+3]) for i in range(0, len(a), 3)]
Sign up to request clarification or add additional context in comments.

3 Comments

Downvote? This produces the exact output requested by the OP.
Maybe it's because of the spurious leading [? (wasn't me btw)
Sneaky.. Bad copy/paste from the interpreter. Another reason copy/paste is bad for you! Thanks for finding the mistake.
4

Reuse!

from itertools import islice

def split_every(n, iterable):
    i = iter(iterable)
    piece = list(islice(i, n))
    while piece:
        yield piece
        piece = list(islice(i, n))

a = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
new_a = [' '.join(slice) for slice in split_every(3, a)]

Mainly using this.

1 Comment

This also produces the exact output. :/

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.