bac
bac

Reputation: 625

Joining Subsequent List Elements - Python

Is there a command to merge subsequent elements in a list - ie in a list ['AA', 'BB', 'C', 'D'] how would one merge the first two elements (or any others, depending on the code) in the list, leaving a list like ['AABB', 'C', 'D'] ? Thanks!

Upvotes: 1

Views: 1869

Answers (3)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29131

You can try the following if you don't care about init list:

>>> a = ['AA', 'BB', 'C', 'D']
>>> a[0] += a.pop(1)

If you want to get new one and leave initList as is you can use something like this(note that this is just a sample):

a = ['AA', 'BB', 'C', 'D']
outList = a[:] # make a copy of list values
outList[0] += outputList.pop(1)

Or in some cases you can try to use something like this too:

from itertools import groupby

a = ['AA', 'BB', 'C', 'D']
res = [''.join((str(z) for z in y)) for x, y in groupby(a, key = lambda x: len(x) == 2)]

Upvotes: 2

Dan D.
Dan D.

Reputation: 74685

>>> a = ['AA', 'BB', 'C', 'D']
>>> a[0:2] = [''.join(a[0:2])]
>>> a
['AABB', 'C', 'D']

Upvotes: 5

Adrien Plisson
Adrien Plisson

Reputation: 23313

here is a python 3.x solution which uses iterators, and thus is compatible with any generator object (like range object...):

def merger(iterable, index=0, length=1):
    it = iter(iterable)
    for count in range(index):
        yield next(it)
    merged = next(it)
    for count in range(length-1):
        merged += next(it)
    yield merged
    for item in it:
        yield item

Upvotes: 1

Related Questions