我有一个嵌套列表a = [1, 2, [3, 4], 5],我想应用一个函数来将每个数字提高到 2 的幂。结果将是这样的:
a = [1, 4, [9, 16], 25]
Run Code Online (Sandbox Code Playgroud)
我试过了,a = [list(map(lambda x : x * x, x)) for x in a]但它给出了这个错误
a = [1, 4, [9, 16], 25]
Run Code Online (Sandbox Code Playgroud)
我们如何解决这个问题?如何在嵌套列表上应用函数?
您可能需要一个递归函数来区分列表和标量:
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]
Run Code Online (Sandbox Code Playgroud)
顺便说一下,这种方法适用于任意嵌套列表。
这是一个更通用的解决方案:
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]
Run Code Online (Sandbox Code Playgroud)