gpt4 book ai didi

python - 将函数应用于任意嵌套列表的每个项目

转载 作者:行者123 更新时间:2023-12-01 08:31:28 25 4
gpt4 key购买 nike

我有一个嵌套列表 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

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

最佳答案

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

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]

关于python - 将函数应用于任意嵌套列表的每个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53899371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com