I'm trying to apply a function to every element of a list containing arbitrary sub-levels of sublists. Like so.
a = [1,2,3]
b = [[1,2,3],[4,5,6]]
c = [[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]]
function = lambda x: x+1
def apply(iterable,f):
# do stuff here
print(apply(a,function)) # [2,3,4]
print(apply(b,function)) # [[2,3,4],[5,6,7]]
print(apply(c,function)) # [[[2,3,4],[5,6,7]],[[8,9,10],[11,12,13]]]
basically i can't find a way to write the apply
function. I tried with numpy, but that's not the solution, of course, because the contents of the list could also be strings, objects ...
Sounds like recursion should be able to solve that:
a = [1,2,3]
b = [[1,2,3], [4,5,6]]
c = [[[1,2,3], [4,5,6]], [[7,8,9], [10,11,12]]]
f = lambda x : x+1
def apply(iterable, f):
# suggestion by Jérôme:
# from collections.abc import Iterable and use
# isinstance(iterable, collections.abc.Iterable) so it works for tuples etc.
if isinstance(iterable, list):
# apply function to each element
return [apply(w, f) for w in iterable]
else:
return f(iterable)
print(apply(a, f)) # [2,3,4]
print(apply(b, f)) # [[2,3,4],[5,6,7]]
print(apply(c, f)) # [[[2,3,4],[5,6,7]],[[8,9,10],[11,12,13]]]