apply a function over each element of an iterable with sublists

Viewed 590

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 ...

4 Answers

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]]]

Here is one way to do it. Note that strings are also iterable so depending on your use case you might need to add more checking.

def apply(iterable, f):
    try:
        iterator = iter(iterable)
        for i in iterator:
            apply(i, f)
    except Exception as e:
        f(iterable)

c = [[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]]
apply(c, print)

Give this recursion a shot:

def apply(it, func):
    try:
        return [apply(e) for e in it]
    except TypeError:
        return func(it)

Note that this will iterate over any iterable unless you specify otherwise, for example you can check in the beginning if it is a dict and just apply it the func on it.. add

if isinstance(it,dict):
    func(it)

If all your nested lists are the same shape you should be able to do this with numpy:

import numpy as np

ary = np.array([['a', 'b'], ['c', 'd'], ['e', 'f']])
res = np.vectorize(lambda c: c + ':)')(ary)
print(res)
# [['a:)' 'b:)']
#  ['c:)' 'd:)']
#  ['e:)' 'f:)']]
Related