Python 列表理解与嵌套循环,简洁性/效率

标签 python code-complexity

以下 2 个方法执行相同的操作。就时间/空间复杂度而言,哪一种更有效?

** Method A**
for student in group.students:
    for grade in student.grades:
        some_operation(grade)

** Method B**
for grade in [grade for student in group.students for grade in student.grades]
    some_operation(grade)

最佳答案

方法 B 看起来很奇怪而且多余。您可以将其缩短为:

[some_operation(grade) for student in group.students for grade in student.grades]

但是方法 A 更好,因为它不创建列表。简单地列出一个列表然后扔掉会让读者感到困惑并且浪费内存。

关于Python 列表理解与嵌套循环,简洁性/效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39779757/

相关文章:

java - Stream API 使用的方便复杂性?

time-complexity - 这个递归斐波那契的 Big-O 时间复杂度?

python - 如何确定输入何时是字母?

python - 是否可以将 PCA 应用于任何文本分类?

python - 如何从 Jenkins 的特定构建中获取分支名称?

python - set() 函数算法和 "&"运算符一起使用时的复杂性

node.js - 导出模块时减少函数长度

linq - 如何将复杂的查询分解为不同的方法以降低代码复杂性

python - 我可以在 Python 中运行 bash 脚本并保留它导出的任何环境变量吗?

python - 当存在 NaN 时,matplotlib scatter 会改变颜色代码