python - 列表理解/生成器中的海象赋值表达式

标签 python

我正在尝试将 foo_list 的每个元素传递给函数 expensive_call,并获取其输出为 expensive_call 的所有项的列表是真实的。我正在尝试通过列表理解来做到这一点,这可能吗?像这样的东西:

像这样:

 result_list = [y := expensive_call(x) for x in foo_list if y]

或者……

 result_list = [y for x in foo_list if y := expensive_call(x)]

注意:这不是解决方案,因为它调用了两次昂贵的调用:

 result_list = [expensive_call(x) for x in foo_list if expensive_call(x)]

在有人推荐 none list comprehension 之前,我知道可以这样做:

result_list = []
for x in foo_list:
   result = expensive_call(x)
   result and result_list.append(result)

最佳答案

从上面引用:

result_list = [y for x in foo_list if y := expensive_call(x)]

它应该几乎完全按照您的方式工作;只需记住用 := 运算符将赋值括起来,如下所示。

foo_list = [1, 2, 3]
def check(x): return x if x != 2 else None

result_list = [y for x in foo_list if (y := check(x))]
print(result_list)

结果:

[1, 3]

关于python - 列表理解/生成器中的海象赋值表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70760723/

相关文章:

python - 如何为 Pandas Dataframe 中的每一列创建箱线图?

Python/Pandas - 根据列值向 DataFrame 添加计数器

python - Pandas 数据框 : swap column headings by index

python - python中的列表列表,想要对列表中的每个值进行算术运算,然后附加到列表

python - 这个 cudaGetDevice() 失败可能是什么问题。状态 : cudaGetErrorString symbol not found

python - 通过 XML 解析时记录被删除

python - docker中的 flask : different relative import in Dockerfile build and docker-compose

python - df = pd.read_csv ('iris.csv' ) 指向 azure blob 报告中的文件 [errno 2] 没有这样的文件或目录

Python subprocess.Popen 作为 Windows 上的不同用户

python - 用于 Python/IronPython 的 Eclipse 中的 GUI 运行器