【问题标题】:How i can change function to one line in python [duplicate]我如何在python中将函数更改为一行[重复]
【发布时间】:2021-01-12 19:21:07
【问题描述】:
def height (t):
  if not t:
    return 0                                   # (1)
  elif not t.nodes:
    return 1                                   # (2)
  else:
    return 1 + max(height(n) for n in t.nodes) # (3)

大家好,有人可以帮助我并将此功能更改为管道吗? 使用 map , filter , lambda

你不需要写 def height 您只需要使用 lambda 映射过滤器 (PIPLINE)

【问题讨论】:

  • 为什么?单行不等于更好、更快或更易读的代码
  • 我知道,但这是我的使命..
  • 单行是否可以接受?
  • not t 是t is None 的委婉说法,所以t.nodes 的未来使用不会引发AttributeError?
  • 是的,我只需要一行,并且还有一个递归

标签: python python-3.x dictionary filter tree


【解决方案1】:

由于您只在 not t 时返回 0,而在其他情况下您返回 1,您可以使用以下简单行:

return 0 if not t else 1 if not t.nodes else 1 + max(height(n) for n in t.nodes)

【讨论】:

  • 但我需要递归
  • @GalBirka 但我要求你不能在管道中做到这一点?
猜你喜欢
  • 1970-01-01
  • 2019-06-30
  • 2015-09-29
  • 2022-10-18
  • 2019-11-16
  • 1970-01-01
  • 1970-01-01
  • 2013-04-14
  • 2018-04-05
相关资源
最近更新 更多