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!
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())
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)))
Code -
def solve(x):
if isinstance(x, int):
return str(x)
return ''.join(solve(y) for y in x)
print(solve(a))
Output -
1001010010100
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With