【问题标题】:python 3.7 single line for comprehension [duplicate]python 3.7单行理解[重复]
【发布时间】:2020-08-12 13:36:33
【问题描述】:

我的代码如下所示:

x = ["hello","world","if"]
test = [len(word) for word in x if len(word)>4]
print(test)

在我的原始代码中“len”是一个非常复杂的函数,有没有办法只计算 len 一次? 在传统的 for 循环中,可以这样做:

test = []
for word in x:
   temp= len(word)
   if temp > 4:
   test.append(temp)

您能否建议如何在不使用传统 for 循环的情况下达到相同的结果。

谢谢

【问题讨论】:

  • 您是否覆盖了默认的len?据我所知len 实际上被认为是O(1) 计算。此外,“传统的 for 循环”在功能上与列表推导相同,实际上是语法糖
  • 我会以某种方式记住结果,没有内置的方法可以自动为您完成这项工作
  • 对不起,我试图简化事情,看起来我让它们变得更复杂了,在我的情况下我不使用 len 它 some_function(word),所以代码如下所示:[some_function( word) for word in x if some_function(word)>4]
  • 对于像 len 这样的函数来说,计算量并不大。但是对于繁重的功能,您可以使用test = [z for z in [func(y) for y in x] if z>4]

标签: python python-3.x for-loop


【解决方案1】:

您可以使用:= 运算符(在 Python 3.8+ 的情况下):

def my_len(s):
    # ...other complicated computations...
    return len(s)

x = ["hello","world","if"]
test = [l for word in x if (l:=my_len(word))>4]
print(test)

注意:不要覆盖默认的内置函数,在本例中为 len()。其他功能可能依赖它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2021-03-11
    • 2021-06-10
    相关资源
    最近更新 更多