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']
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']
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']
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']
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.
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