python - 将函数应用于任意嵌套列表的每个项目
问题描述
我有一个嵌套列表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]
推荐阅读
- android - Android Studio 3 USB调试离线手机
- spring - 在 Spring Boot 中更改单个控制器的 x-frame-options 标头
- php - 我可以使用 PHP 从谷歌分析中获取唯一用户数据吗
- bash - 循环和 grep 只为最后一行写入输出
- php - 为什么这里的地图反馈 API 会抛出验证异常
- qt - 是什么导致上下文菜单关闭?
- haskell - 如何对列表中的数字求和
- java - 如何使用 Java 在 GCP 上创建云机器学习引擎作业?
- python - 在另一个函数运行时禁止点击事件在小部件上排队
- woocommerce - 可用城市的 woocommerce 列表(可能吗?)