randomal
randomal

Reputation: 6592

Merge elements in list of lists

I have a list of lists like this:

A = [('b', 'a', 'a', 'a', 'a'), ('b', 'a', 'a', 'a', 'a')]

How can I merge the all elements of each inner list to get result A = ['baaaa', 'baaaa']? I would prefer to do this outside of a loop, if possible, to speed up the code.

Upvotes: 0

Views: 1131

Answers (4)

neotam
neotam

Reputation: 2731

If you prefer functional programming. You can use the function reduce. Here is how you can achieve the same result using reduce function as follows.

Note that, reduce was a built in function in python 2.7 but in python 3 it is moved to library functools

from functools import reduce

It is only required to import reduce if you are using python 3 else no need to import reduce from functools

A = [('b', 'a', 'a', 'a', 'a'), ('b', 'a', 'a', 'a', 'a')]
result = [reduce(lambda a, b: a+b, i) for i in A]

If you don't want to use loop or even list comprehension, here is another way

 list(map(lambda i: reduce(lambda a, b: a+b, i), A))

Upvotes: 0

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

If you don't want to write a loop you can use map and str.join

>>> list(map(''.join, A))
['baaaa', 'baaaa']

However, the loop using a list comprehension is almost as short to write, and I think is clearer:

>>> [''.join(e) for e in A]
['baaaa', 'baaaa']

Upvotes: 4

Pankaj Singhal
Pankaj Singhal

Reputation: 16043

You can use str.join:

>>> ["".join(t) for t in A]
['baaaa', 'baaaa']
>>>
>>>
>>> list(map(''.join, A)        #with map
['baaaa', 'baaaa']
>>>
>>> help(str.join)
Help on method_descriptor:

join(...)
    S.join(iterable) -> str

    Return a string which is the concatenation of the strings in the
    iterable.  The separator between elements is S.

>>>

Upvotes: 4

syats
syats

Reputation: 81

Use the join method of the empty string. This means: "make a string concatenating every element of a tuple (for example ('b', 'a', 'a', 'a', 'a') ) with '' (empty string) between each of them.

Thus, what you are looking for is:

 [''.join(x) for x in A]

Upvotes: 1

Related Questions