Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through lists of different lengths which are inside a list [duplicate]

Tags:

python

list

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!

like image 514
kelua Avatar asked May 20 '16 15:05

kelua


4 Answers

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())
like image 99
hilberts_drinking_problem Avatar answered Nov 15 '22 11:11

hilberts_drinking_problem


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)))
like image 21
Jared Goguen Avatar answered Nov 15 '22 12:11

Jared Goguen


Code -

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

print(solve(a))

Output -

1001010010100
like image 1
Vedang Mehta Avatar answered Nov 15 '22 11:11

Vedang Mehta


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)
like image 1
malbarbo Avatar answered Nov 15 '22 10:11

malbarbo