1

I have a list like this:

['Ww','Aa','Bb','Cc','ww','AA','BB','CC']

And continuing in such a pattern, with varying capitals and lowercases. What I want to do is join every four items in this list together. So, the resulting new list (given the one above) would look like this:

['WwAaBbCc', "wwAABBCC']

How would I go about this?

Hersh S.
  • 197
  • 2
  • 10

3 Answers3

4
>>> L = ['Ww','Aa','Bb','Cc','ww','AA','BB','CC']
>>> [''.join(x) for x in zip(*[iter(L)] * 4)]
['WwAaBbCc', 'wwAABBCC']
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
3
my_list = ['Ww','Aa','Bb','Cc','ww','AA','BB','CC']
[''.join(my_list[i:i + 4]) for i in range(0, len(my_list), 4)]
Mike Axiak
  • 11,827
  • 2
  • 33
  • 49
  • Haha just posted my answer to see that you had posted the exact same solution. +1 – Nolen Royalty Apr 10 '12 at 04:04
  • here's the error I get: new_Final = [''.join(final[i:i + 4] for i in range(0, len(final), 4)] ^ SyntaxError: invalid syntax (the arrow points to the last bracket) – Hersh S. Apr 10 '12 at 04:09
1

You can use something like this:

def _get_chunks(lVals, size):
    for i in range(0, len(lVals), size):
        yield lVals[i: i + size]

data = ['Ww','Aa','Bb','Cc','ww','AA','BB','CC']


output = [''.join(chunk) for chunk in _get_chunks(data, 4)]
>>> ['WwAaBbCc', 'wwAABBCC']
Artsiom Rudzenka
  • 27,895
  • 4
  • 34
  • 52