Home > Net >  How can I convert a list of sublists including sublits to a string in Python
How can I convert a list of sublists including sublits to a string in Python

Time:12-19

I would like to convert the following list of sublists inluding sublits including int to a string like the following:

[[[0], [0], [0], [0], [0], [0], '\n'], [[0], [1], [0], [0], [0], [0], '\n'], [[0], [0], [0], [0], [0], [0], '\n'], [[0], [0], [0], [0], [0], [0]]]

should be:

"000000\n
010000\n
000000\n
000000"

I already tried many different ways using .join and str using list compressions and etc. but I couldn't find a solution yet. I'd appreciate any help.

.join() looking in py doc

CodePudding user response:

Assuming l the input, you can use a recursive function, this will work with any arbitrary depth of the lists:

def flatten(l):
    if isinstance(l, list):
        for x in l:
            yield from flatten(x)
    else:
        yield str(l)

out = ''.join(list(flatten(l)))

Output:

'000000\n010000\n000000\n000000'

CodePudding user response:

Another solution:

lst = [
    [[0], [0], [0], [0], [0], [0], "\n"],
    [[0], [1], [0], [0], [0], [0], "\n"],
    [[0], [0], [0], [0], [0], [0], "\n"],
    [[0], [0], [0], [0], [0], [0]],
]


out = []
for subl in lst:
    out.append(
        "".join(str(val[0]) if isinstance(val, list) else val for val in subl)
    )

out = "".join(out)
print(out)

Prints:

000000
010000
000000
000000
  • Related