0

Explanation: There is list (can contain several nested lists, variables, int, str). For example:

b = 15
list = [1,2,3,4,[5,6,7,8,[9,["a",b,"c"],10,11]]]

I would like my input to be:

1, 2, 3 , 4 ,5 ,6, 7, 8, 9, a, b, c, 10, 11

Is there any function that can convert any list with any nested level to a string?

I know in reality it is not the case that will always happen, however we do not always know what is inside of the list to write specific function or iteration/loop.

P.S. I have tried several methods already closed/discussed (join for example) on StackOverflow, however those work only for simple or specific lists.

Thanks in advance.

Edited:

def flatten(lis):
    """Given a list, possibly nested to any level, return it flattened."""
    new_lis = []
    for item in lis:
        if isinstance(item, list):
            new_lis.extend(flatten(item))
        else:
            new_lis.append(item)
    return new_lis
  • There are two steps to this that are both easy, and already answered on Stack Overflow. Just do the two steps separately. First, [flatten the list](http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python). Then, map `str` over all of the elements of the flattened list, and `join` the result. – abarnert Apr 05 '18 at 07:04
  • Thanks. But this does not answers my questions. The case indicated there could be done by 2 loops, what if i have 10 or 20 or even X numbers of nested lists? Also i have here INT so second loop will not work as python cannot iterate through INT. – Saleh Ahmadzada Apr 05 '18 at 07:15
  • @SalehAhmadzada you can find more answers here : http://code.activestate.com/recipes/578948-flattening-an-arbitrarily-nested-list-in-python/ – Vikas Periyadath Apr 05 '18 at 08:53
  • @VikasDamodar Thanks. I have modified solution little bit. You can find it above. – Saleh Ahmadzada Apr 05 '18 at 09:18

1 Answers1

3

A quick solution.

l = [1,2,3,4,[5,6,7,8,[9,["a","b","c"],10,11]]]

v = str(l).replace("[", ",").replace("]", ",").replace("'", "").split(",")
v = [i.strip() for i in v if i.strip()]    #v = filter(None, v)
print(",".join(v))
Rakesh
  • 81,458
  • 17
  • 76
  • 113