[英]How do I transform this lambda function into def format?
I found this answer to a question here ( How to build a recursion for arbitrary lists? ) but I haven't learnt how to use lambdas . 我在这里找到了这个问题的答案( 如何为任意列表建立递归? ),但是我还没有学会如何使用lambdas 。
prune = lambda tree : [prune(branch) for branch in tree if branch != []]
l = [[[[], []], [[], []]], [[], [], []]]
print prune(l)
I checked many websites but I can not seem to manage to transform this into a regular function like: 我检查了许多网站,但似乎无法设法将其转换为常规功能,例如:
def prune(tree):
for branch in tree:
if branch!=[]:
prune(branch)
return branch
print prune([[[[], []], [[], []]], [[], [], []]])
Can someone tell me what are those big square brackets for before prune and at the end? 有人可以告诉我在修剪之前和结束时要用那些大方括号吗?
All you have to do is slap a return
on the front. 您所要做的就是在前面打
return
。
def prune(tree):
return [prune(branch) for branch in tree if branch != []]
If you wanted to decompose the list comprehension —and there's no real reason to—it'd be: 如果您想分解列表的理解 ,并且没有真正的理由,那就是:
def prune(tree):
for branch in tree:
if branch != []:
yield prune(branch)
Or: 要么:
def prune(tree):
branches = []
for branch in tree:
if branch != []:
branches.append(prune(branch))
return branches
lambdas are always easily transform-able into a def with a single return statement: 使用单个return语句,lambda总是很容易转换为def:
f = lambda a: b
is always almost identical to 总是几乎与
def f(a):
return b
If you need to do your example without list comprehension: 如果您需要在没有列表理解的情况下进行示例:
def prune(tree):
ret = []
for branch in tree:
if branch!=[]:
ret.append(prune(branch))
return ret
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.