2

I have a python list of chars and want to join them to create a list of strings of 8 elements each, eg:

x = ['0','0','1','a','4','b','6','2','2','1','4','1','5','7','9','8']

result

['001a4b62', '21415798']
Jacob Vlijm
  • 3,099
  • 1
  • 21
  • 37
omkar joshi
  • 83
  • 2
  • 9

4 Answers4

4

The itertools documentation contains a grouper recipe that groups consecutive items to fixed-sized groups:

from itertools import *

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

Now you can just group into lists of size 8, and turn each one to a string:

>>> [''.join(e) for e in grouper(x, 8)]
['001a4b62', '21415798']
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
4
x = ['0','0','1','a','4','b','6','2','2','1','4','1','5','7','9','8']

Simply:

print(["".join(x[i:i + 8]) for i in range(0, len(x), 8)])
> ['001a4b62', '21415798']
Jacob Vlijm
  • 3,099
  • 1
  • 21
  • 37
1

You can use join to convert an array of characters to a string. Here's how you'd do it in your case -

x = ['0','0','1','a','4','b','6','2','2','1','4','1','5','7','9','8']
i = 0
strlist = []
while i<len(x):
  strlist.append(''.join(x[i:i+8]))
  i+=8

strlist will hold your grouped strings.

Zeokav
  • 1,653
  • 4
  • 14
  • 29
1

First check out the following How to split python list into chunks of equal size?

With this in place you can do in python 3.x, give the above variable x

import operator
import functools
result = map(lambda s: functools.reduce(operator.add, s), zip(*[iter(x)]*8))

In python 2.x you can drop the functools prefix for reduce.

fricke

Community
  • 1
  • 1
fricke
  • 1,330
  • 1
  • 11
  • 21