-1

Given:

[[[[[[[[['A']]]]],[[[[['B']]]]],['C'],[[[[['D']]]]]]

Or something like that. A complicated nested list.

How can I return either:

'ABCD' or ['ABCD']

Recursive function with int is simple enough due to the sum helper function, but I can't imagine how to do this with str.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Charlie
  • 21
  • 6

2 Answers2

1

Here's a recursive method to return a single string

def joinValues(i):
    if isinstance(i, list):
        return ''.join(joinValues(j) for j in i)
    else:
        return i

>>> l = [[[[[[[[['A']]]]],[[[[['B']]]]],['C'],[[[[['D']]]]]]]]]
>>> joinValues(l)
'ABCD'
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

You can use flatten function from compiler.ast module to flatten a nested list,and you can use join() to join your characters :

>>> l=[[[[[[[[['A']]]]],[[[[['B']]]]],['C'],[[[[['D']]]]]]]]]
>>> from compiler.ast import flatten
>>> flatten(l)
['A', 'B', 'C', 'D']
>>> ''.join(flatten(l))
'ABCD'

Note that as mentioned in comment this function has been removed from python3 instead you can use itertools.chain within a recursion function! or as a more various ways you can checkout the duplicated question answers!

Community
  • 1
  • 1
Mazdak
  • 105,000
  • 18
  • 159
  • 188