You can use this function:
def to_int(lst):
for i in lst:
if isinstance(i, list):
yield list(to_int(i))
else:
yield int(i)
Here is a test run:
>>> li = ['0', ['1', '2'], ['3', ['4', '5'], '6', ['7'], '8'], '9']
>>> list(to_int(li))
[0, [1, 2], [3, [4, 5], 6, [7], 8], 9]
Note that this only works for nested lists, and can only perform the int
function. We can make the function more general like so:
def deep_map(lst, f=int): # the parameter `f` is the function
for i in lst:
if isinstance(i, collections.Iterable) and not isinstance(i, str):
yield list(deep_map(i, f))
else:
yield f(i)
This will allow us to use nested collections other than lists (eg tuples), and we can specify our own function to call on the list.