首页 > 解决方案 > 将函数应用于任意嵌套列表的每个项目

问题描述

我有一个嵌套列表a = [1, 2, [3, 4], 5],我想应用一个函数,它将每个数字提高到 2 的幂。结果将是这样的:

a = [1, 4, [9, 16], 25]

我试过a = [list(map(lambda x : x * x, x)) for x in a]但它给出了这个错误

'int' object is not iterable

我们如何解决这个问题?如何在嵌套列表上应用函数?

标签: python

解决方案


您可能需要一个区分列表和标量的递归函数:

def square(item):
    if isinstance(item, list):
        return [square(x) for x in item]
    else:
        return item * item

square(a)
#[1, 4, [9, 16], 25]

顺便说一下,这种方法适用于任意嵌套的列表。

这是一个更通用的解决方案:

def apply(item, fun):
    if isinstance(item, list):
        return [apply(x, fun) for x in item]
    else:
        return fun(item)

apply(a, lambda x: x * x)
#[1, 4, [9, 16], 25]

推荐阅读