Chengming Gu
Chengming Gu

Reputation: 67

How to apply a function to a list within a list

I have a list and a function:

t = [3, [1], [2, [1], [1]]]

f = lambda x: x**2

I want the result like this:

[9, [1], [4, [1], [1]]]

I tried to use map function but it did not seem to work

I got a type error when I do this:

list(map(f, t))

Upvotes: 2

Views: 87

Answers (4)

Kasravnd
Kasravnd

Reputation: 107297

You can use a recursion function and a list comprehension as following:

def nested_pow(arr, p):
   return [pow(i, p) if isinstance(i, int) else nested_pow(i, p) for i in arr] 

Demo:

In [34]: nested_pow(t, 2)
Out[34]: [9, [1], [4, [1], [1]]]

In [35]: nested_power(t, 3)
Out[35]: [27, [1], [8, [1], [1]]]

In [36]: nested_power(t, 10)
Out[36]: [59049, [1], [1024, [1], [1]]]

Upvotes: 5

Ajax1234
Ajax1234

Reputation: 71461

You need to change your function to be recursive so that it can traverse data of an arbitrary depth:

f = lambda x:x*x if not isinstance(x, list) else [f(i) for i in x]
t = [3, [1], [2, [1], [1]]]
new_result = list(map(f, t))

Output:

[9, [1], [4, [1], [1]]]

Upvotes: 4

Aran-Fey
Aran-Fey

Reputation: 43196

You could write a recursive variant of the map function:

def recursive_map(func, iterable, *, sequence_types=(list,tuple)):
    for value in iterable:
        # if's a sequence, recurse
        if isinstance(value, sequence_types):
            cls = type(value)
            values = recursive_map(func, value, sequence_types=sequence_types)
            yield cls(values)
        else:  # if it's not a sequence, call the function on it
            yield func(value)
t = [3, [1], [2, [1], [1]]]
f = lambda x: x**2

print(list(recursive_map(f, t)))
# output: [9, [1], [4, [1], [1]]]

Upvotes: 5

Barmar
Barmar

Reputation: 781210

if the element of t is another list, you need to map the function, not call the function. If you want this to handle arbitrary levels of nesting, f needs to be recursive.

t = [3, [1], [2, [1], [1]]]

def f(x):
    if isinstance(x, list):
        return map(f, x)
    else:
        return x**2

print(map(f, t))

Upvotes: 7

Related Questions