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.

Philippe Remy
  • 2,967
  • 4
  • 25
  • 39
Natsume
  • 881
  • 3
  • 15
  • 22
  • What have you tried so far? Are you trying to merge groups of always three columns? – Pierre GM Sep 06 '12 at 06: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? – Blckknght Sep 06 '12 at 06: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. – voithos Sep 06 '12 at 06:17
  • im not good in english sorry :P – Natsume Sep 06 '12 at 06:17
  • Yeah, I'm sorry about that. My comment ended up sounding much harsher than I intended it to. After seeing the title I was all ready to give an answer using `zip` and when I reread the question I realized that it wouldn't be right at all. – Blckknght Sep 06 '12 at 06:23
  • Why do you say a while loop is inefficient? It would be a strange choice for this task, but it's not inefficient. – John La Rooy Sep 06 '12 at 06:26
  • problem solved, thanks you all who answered my question :DD – Natsume Sep 06 '12 at 06:26
  • 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. – Aesthete Sep 06 '12 at 06:30
  • I agree this should be closed as a duplicate of the first link, but does not directly relate to **merge two lists** in python. – Aesthete Sep 06 '12 at 12:57

2 Answers2

19
[' '.join(a[i:i+3]) for i in range(0, len(a), 3)]
cspolton
  • 4,495
  • 4
  • 26
  • 34
Aesthete
  • 18,622
  • 6
  • 36
  • 45
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.

Community
  • 1
  • 1
voithos
  • 68,482
  • 12
  • 101
  • 116