Home > Enterprise >  Joining elements together in list but keeping original layout
Joining elements together in list but keeping original layout

Time:07-01

So I have a list that looks like this:

list = ["a","b","c", etc] 

I would like to join the elements together but keep the original layout, so the final output should look like:

list=["a","ab","abc" etc]. 

Does anyone have a concise way of doing this?

CodePudding user response:

You can use list comprehension and join() function to concatenate resulting strings:

l = ["a","b","c"]

out = [''.join(l[:i]) for i in range(1, len(l) 1)]
print(out)

Output:

['a', 'ab', 'abc']

CodePudding user response:

You can use itertools.accumulate:

>>> import itertools
... 
... lst = ['a', 'b', 'c', 'etc']
... list(itertools.accumulate(lst))
['a', 'ab', 'abc', 'abcetc']

This is exactly what it does.

CodePudding user response:

>>> array = ["a","b","c","d","e"]
>>> for i, v in enumerate(array[1:], 1):
...     array[i] = ''.join([array[i-1],v])
... 
>>> array
['a', 'ab', 'abc', 'abcd', 'abcde']

CodePudding user response:

my_list = ["a","b","c"]

def foo(my_list):
    output = []
    for index,item in enumerate(my_list):
        if index == 0:
            output.append(item)
        else:
            output.append(output[index-1]   item )
    return output

print(foo(my_list)) #prints ['a', 'ab', 'abc']
  • Related