aceminer
aceminer

Reputation: 4295

concatenating multiple items in list

I would like to know if theres any possible way to concatenate multiple item in a list and returning another list in a pythonic way.

E.g

[a,b,c,d,e]

If i were to have an output of

[ab,cd,e] 

My code would be something like this:

x = ['a','b','c','d','e']
a = []
for i in range(0,len(x),2):
    if i + 2 >= len(x):
        a.append(x[i])
    else:
        a.append(x[i] + x[i+1])

Output of a:
['ab','cd','e']

Is there a better way or more pythonic way to do this? I am using python2.7

Upvotes: 0

Views: 51

Answers (2)

DaoWen
DaoWen

Reputation: 33019

The Python documentation's itertools recipes section has a grouper function you might find useful:

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)

Here's how I'd use it:

from itertools import izip_longest
import operator

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)

def concat_groups(iterable, n):
    groups = grouper(iterable, n, fillvalue='')
    return [ ''.join(g) for g in groups ]

x = ['a','b','c','d','e']
concat_groups(x, 2) # ==> ['ab', 'cd', 'e']
concat_groups(x, 3) # ==> ['abc', 'de']

Upvotes: 1

chepner
chepner

Reputation: 531175

Use join to concatenate slices of the input list.

n=2  # or 5, or 10
output = [ ''.join(input[i:i+n]) for i in range(0, len(input), n)]

Upvotes: 1

Related Questions