waas1919 waas1919 - 1 year ago 65
Python Question

Python - Convert array with list with different sizes to string

I have a Python array that contains a lot of lists, with different sizes.

myArray = [('Hello my name is ', ('Bond, James', 'Bond. It is ', '16:40', ' now'), '!!!')]

Question: What is the best way (more optimized) to get the bellow output, without creating a loop method which will append every value to a string?

I would like to see the following output:

"Hello my name is Bond, James Bond. It is 16:40 now!!!"


First, you have to flatten the nested list to a 'flat' list. Assuming that your list contains either strings or other lists (or tuples), you could use a function like this:

def flatten(lst):
    for x in lst:
        if isinstance(x, str):
            yield x
            for y in flatten(x):
                yield y

Incidentally, there also seems to be a function for this in the compiler.ast module, so alternatively you could just import that function and use it. However, this module is deprecated and has been removed in Python 3.

from compiler.ast import flatten

Either way, after the list has been flattened, you just have to join the segments to one string.

>>> list(flatten(myArray))
['Hello my name is ', 'Bond, James', 'Bond. It is ', '16:40', ' now', '!!!']
>>> ''.join(flatten(myArray))
'Hello my name is Bond, JamesBond. It is 16:40 now!!!'