Python, How to concatenate successive and similar elements of a list?

For example: the input is :

['1','2','3','3','7','7','4']

I want this output:

['1','2','33','77','4']

I made this function but it works only if len of the list is power of 2

def function(L):
    M=[]
    for i in range(0,len(L),2):
            if L[i]==L[i+1]:
                M.append(L[i]+L[i+1])
            else:
                M.append(L[i])
                M.append(L[i+1])
    return M  

Upvotes: 0

Views: 98

Answers (5)

CallMePerox
CallMePerox

Reputation: 63

A counter would probably serve you well, but if you want a solution similar to yours and import-less know that while loops are much more appropiate for codes like yours:

def function(L):
    M = []
    i = 0
    while i < len(L):
        if i+1 < len(L):
            if L[i]==L[i+1]:
                M.append(L[i]+L[i+1])
                i += 1
            else:
                M.append(L[i])
            i += 1
        else:
            M.append(L[i])
            break
    return M

This is not the most efficient way to face the problem, but comes straight from the code you programmed, just to show how in this case you could have found a solution (again, probably not quite the best one) using a while loop instead of a for loop, since it allows you to modify i's value inside the loop.

Upvotes: 2

Kim Mens
Kim Mens

Reputation: 335

I would suggest splitting the problem in two subproblems. One is to concatenate a series of similar elements (auxiliary function), the other is to advance through the list to the next dissimilar element and to create the result list:

def function(L) :
    if L == [] :
        return []
    else :
        (j,val) = concatvalues(L)
        M = [val]
        M.extend(function(L[j:]))
        return M

def concatvalues(L) :
    j = 1
    s = L[0]
    while j < len(L) and L[j] == L[0] :
        s += L[j]
        j += 1
    return (j,s)

print(function(['1','2','3','3','7','7','4']))

Upvotes: 0

Fedortaf
Fedortaf

Reputation: 15

This function works

def function(L):
  M = []
  K = L
  for el in K:
    repet = K.count(el)
    K.remove(el)
    M.append(el*repet)
  return M

*Updated

Upvotes: -2

Błotosmętek
Błotosmętek

Reputation: 12927

import itertools
def function(L):
    return [ ''.join(g) for k, g in itertools.groupby(L) ]

print(function(['1','2','3','3','7','7','4']))

Upvotes: 3

Surya Tej
Surya Tej

Reputation: 1382

This solution concatenates all similar elements in the list. I used Collections module to identify the similar elements and concatenated as per your need

>>> from collections import Counter
>>>
>>> a = ['1','2','3','3','7','7','4']
>>> Counter(a)
Counter({'3': 2, '7': 2, '1': 1, '2': 1, '4': 1})


>>> b = Counter(a)
>>> for ele in Counter(a):
...  print (ele, b[ele])
...
1 1
2 1
3 2
7 2
4 1
>>>
>>> c = [str(ele)*int(b[ele]) for ele in b]
>>> c
['1', '2', '33', '77', '4']
>>>

Upvotes: 0

Related Questions