5

I have the following list:

a = [[1, [0], [0], [1, [0]]], [1, [0], [0], [1, [0]]], [1, [0], [0]]]

and I would like to take all the integers and make a string out of them:

b = '1001010010100'

Is there any way I can do this? Thank you in advance!

kelua
  • 283
  • 1
  • 4
  • 9
  • I think the more general question here is how to iterate over n-dimensional lists. Very good question... – Oisin May 20 '16 at 15:58

4 Answers4

22

Here is a rebellious approach:

a = [[1, [0], [0], [1, [0]]], [1, [0], [0], [1, [0]]], [1, [0], [0]]]
b = ''.join(c for c in str(a) if c.isdigit())
hilberts_drinking_problem
  • 11,322
  • 3
  • 22
  • 51
5

You can write a function that recursively iterates through your nested listed and tries to convert each element to an iterator.

def recurse_iter(it):
    if isinstance(it, basestring):
        yield it
    else:
        try:
            for element in iter(it):
                for subelement in recurse_iter(element):
                    yield subelement
        except TypeError:
            yield it

This hideous function will produce a list of the strings and non-iterable members in an object.

a = [[1, [0], [0], [1, [0]]], [1, [0], [0], [1, [0]]], [1, [0], [0]]]
list(recurse_iter(a))
# [1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0]

Converting this to a string is straight forward enough.

''.join(map(str, recurse_iter(a)))
Jared Goguen
  • 8,772
  • 2
  • 18
  • 36
  • While it works for this case, a general solutions should probably check if an element is a string so that it doesn't start yielding individual characters. – Brian Schlenker May 20 '16 at 16:02
  • @BrianSchlenker That case will cause an infinite recursion. I'll update in a second. – Jared Goguen May 20 '16 at 16:03
  • I like this answer since it gives you the option to [conditionally] modify all items in the list, no matter how deep they are. – Oisin May 20 '16 at 16:16
1

Code -

def solve(x):                                                        
    if isinstance(x, int):
        return str(x)
    return ''.join(solve(y) for y in x)

print(solve(a))

Output -

1001010010100
Vedang Mehta
  • 2,214
  • 9
  • 22
1

You are looking for a flatten function:

def flatten_str(x):
    if isinstance(x, list):
        return "".join(flatten_str(a) for a in x)
    else:
        return str(x)
malbarbo
  • 10,717
  • 1
  • 42
  • 57