python - 如何将此 lambda 函数转换为 def 格式?
问题描述
我在这里找到了一个问题的答案(如何为任意列表构建递归?),但我还没有学会如何使用lambdas。
prune = lambda tree : [prune(branch) for branch in tree if branch != []]
l = [[[[], []], [[], []]], [[], [], []]]
print prune(l)
我检查了许多网站,但似乎无法将其转换为常规功能,例如:
def prune(tree):
for branch in tree:
if branch!=[]:
prune(branch)
return branch
print prune([[[[], []], [[], []]], [[], [], []]])
有人能告诉我修剪之前和结尾的那些大方括号是什么吗?
解决方案
你所要做的就是return
在前面拍一个耳光。
def prune(tree):
return [prune(branch) for branch in tree if branch != []]
如果你想分解列表推导——并且没有真正的理由——那就是:
def prune(tree):
for branch in tree:
if branch != []:
yield prune(branch)
或者:
def prune(tree):
branches = []
for branch in tree:
if branch != []:
branches.append(prune(branch))
return branches
推荐阅读
- android - Android 自定义显式意图
- apache-spark - 如何在 Pyspark 中按元素连接两个 ArrayType(StringType()) 列?
- python - Pandas read_csv:列被导入为行
- java - 在单个 jUnit 测试中运行多个 Jetty 服务器
- api - 如何在父级中获取正确的数组对象
- python - numpy数组中的like语句如何写一个案例
- python - 从 Windows 10 执行行运行 python 脚本(WIN + R 面板)
- ios - Swift:如何提高从文档中加载图像的速度?
- git - 从某个目录中的另一个分支签出所有更改的文件
- php - 如何避免 Composer 出现“无法扫描内部的类”错误?